FileReader 是什么?干嘛用的?

📁 FileReader 是什么?干嘛用的?

📌 整理不易,点赞、收藏、关注,前端小白也能轻松学会文件处理!


🎯 一、FileReader 是干什么的?

在前端开发中,如果用户通过 <input type="file"> 上传了文件,比如图片、PDF、Excel,我们如何在不发送到后端的前提下就读取这个文件内容呢?

答案就是:用 FileReader

👉 简单说,它可以让你:

能力举例
读文件内容读取文本文件、图片、视频等
以不同格式读取文本、Base64、二进制等
不刷新页面处理文件比如预览上传的图片或文本

📦 二、FileReader 是什么东西?

FileReader 是浏览器内置的一个,你可以通过 new FileReader() 创建它的对象:

const reader = new FileReader()

就像你用:

const img = new Image()
const xhr = new XMLHttpRequest()

FileReader 是专门用来读取文件对象(File 或 Blob)内容的。


🧠 三、FileReader 能读什么?

它能读取的是这些类型:

  • 来自 <input type="file"> 选择的文件
  • new Blob() 生成的二进制数据
  • new File() 构造的文件对象
<input type="file" id="myFile">
const file = document.getElementById('myFile').files[0]
const reader = new FileReader()
reader.readAsText(file)  // 就能读出这个文件的内容

🔍 四、常用的读取方法(4 个)

方法名作用结果类型
readAsText(file)读取为纯文本(utf-8)string
readAsDataURL(file)读取为 base64 编码(用于图片预览)string
readAsArrayBuffer(file)读取为二进制流(适合音视频)ArrayBuffer
readAsBinaryString(file)读取为二进制字符串(不推荐)string

🧪 五、FileReader 使用的完整套路(带事件监听)

const input = document.getElementById('myFile')
input.addEventListener('change', function () {
  const file = this.files[0]
  const reader = new FileReader()

  reader.readAsText(file) // 或 readAsDataURL(file)

  reader.onload = function () {
    console.log('文件读取成功:', reader.result)
  }

  reader.onerror = function () {
    console.error('文件读取失败!')
  }
})

✅ 每次读取文件都是异步的(不阻塞页面),读取结果通过 reader.result 拿到。


🎨 六、实战示例:上传图片预览

<input type="file" id="upload">
<img id="preview" style="max-width: 200px;">
document.getElementById('upload').addEventListener('change', function () {
  const file = this.files[0]
  const reader = new FileReader()

  reader.readAsDataURL(file) // 将图片读成 base64

  reader.onload = function () {
    document.getElementById('preview').src = reader.result
  }
})

📌 这样你在选择图片时,就可以马上预览,不需要上传到服务器!


🧠 七、总结一下(最适合小白记住)

关键词你该记住的
FileReader 是什么?读取用户本地文件的工具
怎么创建?new FileReader()
怎么读取?.readAsText().readAsDataURL()
结果在哪?reader.result 里,通过 onload 拿到
能干嘛?实现图片预览、读取 Excel 文本内容、音视频文件等

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值