📁 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 文本内容、音视频文件等 |