FileReader 是一种异步文件读取机制,结合input:file可以很方便的读取本地文件。
一、input:file简介
<input type="file" id="inputBox">
点击按钮上传一个文件后,在控制台打印inputBox.files,如下:
可以发现input.files是一个数组,由传入的file对象组成。每个file对象包含以下属性:
lastModified:数值,表示最近一次修改时间的毫秒数;
lastModifiedDate:对象,表示最后一次表示最近一次修改时间的Date对象(高程中说是字符串,根据上图可看出应该为对象,为了层级清晰未对其展开,大家可自行查看,其可调用Date对象的有关方法,例如getDay方法);
name:本地文件系统中的文件名;
size:文件的字节大小;
type:字符串,文件的MIME类型;
weblitRelativePath:此处为空;当在input上加上webkitdirectory属性时,用户可选择文件夹,此时weblitRelativePath表示文件夹中文件的相对路径。比如:
<input type="file" id="inputBox" webkitdirectory>
可看出,此时weblitRelativePath表示当前file对象的文件在文件夹中的路径。
二、FileReader
以上file对象只获取到了对文件的描述信息,但没有获得文件中的数据,而inputBox.value也只是保存的是文件的绝对路径。我们可以通过html5提供的FileReader读取到文件中的数据。
首先创建一个FileReader实例:
let reader = new FileReader();
FileReader提供了如下方法:
readAsArrayBuffer(file) | 按字节读取文件内容,结果用ArrayBuffer对象表示 |
readAsBinaryString(file) | 按字节读取文件内容,结果为文件的二进制串 |
readAsDataURL(file) | 读取文件内容,结果用data:url的字符串形式表示 |
readAsText(file,encoding) | 按字符读取文件内容,结果用字符串形式表示 |
abort() | 终止文件读取操作 |
readAsDataURL较为常用,这里只对其进行说明。
readAsDataURL会将文件内容进行base64编码后输出:
var inputBox = document.getElementById("inputBox");
inputBox.addEventListener("change",function(){
let reader = new FileReader();
reader.readAsDataURL(inputBox.files[0]);//发起异步请求
reader.onload = function(e){
//读取完成后,数据保存在对象的result属性中
console.log(e.target.result);
console.log(this.result);
}
})
控制台为当前所传文件的base64编码表示。由于媒体文件的src属性,可以通过采用网络地址或base64的方式显示,因此我们可以利用readAsDataURL实现对图片的预览。
<input type="file" id="inputBox">
<img src="" id="img">
var inputBox = document.getElementById("inputBox");
var img = document.getElementById("img");
inputBox.addEventListener("change",function(){
let reader = new FileReader();
reader.readAsDataURL(inputBox.files[0]);//发起异步请求
reader.onload = function(e){
//读取完成后,数据保存在对象的result属性中
console.log(e.target.result);
img.src = e.target.result;
}
})
如上,只需将读取的结果赋给图片的src属性,即可预览图片: