极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。
山月训练营之面试直通车 服务上线了,从准备简历、八股文准备、项目经历准备、面试、面经、面经解答、主观问题答复、谈薪再到入职的一条龙服务。

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

Issue

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

<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();
Last Updated: 11/27/2021, 6:11:48 PM