JavaScript

超轻量级php框架startmvc

JS+HTML5 FileReader对象用法示例

更新时间:2020-05-04 21:24:01 作者:startmvc
本文实例讲述了JS+HTML5FileReader对象用法。分享给大家供大家参考,具体如下:FileReader实例

本文实例讲述了JS+HTML5 FileReader对象用法。分享给大家供大家参考,具体如下:

FileReader 实例中有四个方法来读取文件数据

1、readAsBinaryString(Blob|File) 2、readAsDataURL(Blob|File) 3、readAsText(Blob|File) 4、readAsArrayBuffer(Blob|File)

FileReader 实例包含很多事件(onerror, onprogress, onload[result]


<input name="file" id="uploadFile" />


var file = document.getElementById("uploadFile");
var bufferSize = 1024;
var pos = 0;
var onload = function(e) {
 console.log("Read", e.target.result);
 var img = document.createElement("img");
 img.src = e.target.result;
 img.width = 300;
 img.height = 300;
 document.body.appendChild(img);
};
var onerror = function() {}
var onprogress = function(e) {}
file.onchange = function() {
 if (file.files) file = file.files[0];
 while (pos < file.size) {
 var reader = new FileReader();
 reader.onload = onload;
 reader.onerror = onerror;
 /*reader.readAsText(file.slice(pos, bufferSize));
 pos += bufferSize; */
 reader.readAsDataURL(file);
 pos = file.size + 1;
 }
}

JS HTML5 FileReader对象