高级前端
js
【Q479】前端上传文件时如何读取文件内容

前端上传文件时如何读取文件内容

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 487 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

<input type="file" id="input" onchange="handleFiles(this.files)" />

在浏览器中,通过 input[type=file] 来点击上传文件,此时监听 onChange 事件,可以获取到 File 对象,其中从中可以读取文件内容

而读取文件内容,需要转化 File/BlobText,一般使用以下两种方案

FileReader API

这是最常用处理上传文件的 API,但是却繁琐冗余难记,每次使用基本上都要查文档!

FileReader API 用以读取 File/Blob 内容,正因为繁琐难记,以下实现一个 readBlob 函数读取内容。

function readBlob(blob) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = function (e) {
      resolve(e.target.result);
    };
    reader.readAsText(blob);
  });
}

Response API

而是用 Response API 只需要一行内容

const readBlob = (blob) => new Response(blob).text();