filereader api 类型

filereader类似XMLHttpRequest,只是它用来从文件系统读取文件,提供了不同的方法去读取文件数据:
1、readAsText
2、readAsDataURL
3、readAsBinaryString
4、readAsArrayBuffer

 

读取的过程是异步的,有一些事件可以监听,progress,error,load等

 

progress事件没50毫秒触发一次,也有lengthComputable,loaded,total属性,可以在result里查看到目前读取了多少数据。

 

举例:
var filesList = document.getElementById(“files-list”);
EventUtil.addHandler(filesList, “change”, function(event){
var info = “”,
output = document.getElementById(“output”),
progress = document.getElementById(“progress”),
files = EventUtil.getTarget(event).files,
type = “default”,
reader = new FileReader();
if (/image/.test(files[0].type)){
reader.readAsDataURL(files[0]);
type = “image”;
} else {
reader.readAsText(files[0]);
type = “text”;
}
reader.onerror = function(){
output.innerHTML = “Could not read file, error code is “ +
reader.error.code;
};
reader.onprogress = function(event){
if (event.lengthComputable){
progress.innerHTML = event.loaded + “/” + event.total;
}
};
reader.onload = function(){
var html = “”;
switch(type){
case “image”:
html = “<img src=\”” + reader.result + “\”>”;
break;
case “text”:
html = reader.result;
break;
}
output.innerHTML = html;
};
});

 

读取过程中也是可以用abort来中断。最后不管是load,error,abort,都会触发loadend事件,意味着操作结束

 
 

如果需要读取部分内容的话,可以使用Blob上的slice方法。slice方法返回一个 Blob的实例。Blob类型实际上是file类型的super type。

 

function blobSlice(blob, startByte, length){
if (blob.slice){
return blob.slice(startByte, length);
} else if (blob.webkitSlice){
return blob.webkitSlice(startByte, length);
} else if (blob.mozSlice){
return blob.mozSlice(startByte, length);
} else {
return null;
}
}

 

读取文件前32位数据:
var filesList = document.getElementById(“files-list”);
EventUtil.addHandler(filesList, “change”, function(event){
var info = “”,
output = document.getElementById(“output”),
progress = document.getElementById(“progress”),
files = EventUtil.getTarget(event).files,
reader = new FileReader(),
blob = blobSlice(fi les[0], 0, 32);
if (blob){
reader.readAsText(blob);
reader.onerror = function(){
output.innerHTML = “Could not read file, error code is “ +
reader.error.code;
};
reader.onload = function(){
output.innerHTML = reader.result;
};
} else {
alert(“Your browser doesn’t support slice().”);
}
})

上一篇:[leetcode-494-Target Sum]


下一篇:poj 1265 Area(Pick定理)