FileReader:readAsText() 方法
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
备注: 此特性在 Web Worker 中可用。
FileReader 接口的 readAsText() 方法用于读取指定的 Blob 或 File 对象的内容。当读操作完成时,readyState 属性更改为 DONE,并触发 loadend 事件,并且 result 属性包含表示文件内容的文本字符串。
备注:
Blob.text() 方法是一种较新的基于 Promise 的 API,用于将文件读取为文本。
备注:
该方法将整个文件的内容加载到内存中,不适合大文件。对于大文件,首选使用 readAsArrayBuffer()。
语法
js
readAsText(blob)
readAsText(blob, encoding)
参数
blobencoding可选-
指定用于返回数据的编码的字符串。如果未指定此参数,则默认情况下假定为 UTF-8。
返回值
无(undefined)。
示例
>HTML
html
<input type="file" onchange="previewFile()" /><br />
<p class="content"></p>
JavaScript
js
function previewFile() {
const content = document.querySelector(".content");
const [file] = document.querySelector("input[type=file]").files;
const reader = new FileReader();
reader.addEventListener(
"load",
() => {
// 然后这将显示一个文本文件
content.innerText = reader.result;
},
false,
);
if (file) {
reader.readAsText(file);
}
}
结果
规范
| Specification |
|---|
| File API> # readAsDataText> |
浏览器兼容性
Loading…