FileReader接口主要用來把文件對象或者Blob對象讀入內存,並使用屬性方法從文件或Blob中讀取數據。它繼承自EventTarget。而且還使用了異步機制的API,使用該API可以在瀏覽器主線程中異步訪問文件系統。
1、FileReader支持的屬性、事件、方法如下:
[Constructor]
interface FileReader: EventTarget {
// async read methods
void readAsArrayBuffer(Blob blob);
void readAsBinaryString(Blob blob);
void readAsText(Blob blob, optional DOMString encoding);
void readAsDataURL(Blob blob);
void abort();
// states
const unsigned short EMPTY = 0;
const unsigned short LOADING = 1;
const unsigned short DONE = 2;
readonly attribute unsigned short readyState;
// File or Blob data
readonly attribute any result;
readonly attribute DOMError error;
// event handler attributes
attribute [TreatNonCallableAsNull] Function? onloadstart;
attribute [TreatNonCallableAsNull] Function? onprogress;
attribute [TreatNonCallableAsNull] Function? onload;
attribute [TreatNonCallableAsNull] Function? onabort;
attribute [TreatNonCallableAsNull] Function? onerror;
attribute [TreatNonCallableAsNull] Function? onloadend;
};
2、事件
onabort 數據讀取中斷觸發
onerror 數據讀取出錯時觸發
onloadstart 數據讀取開始時觸發
onprogress 數據讀取中
onload 數據讀取成功完成時觸發
onloadend 數據讀取完成時觸發
3、方法
方法名 參數 描述
readAsBinaryString file 將文件讀取爲二進制代碼
readAsArrayBuffer blob 將文件讀取問ArrayBuffer
readAsText file,[encoding] 將文件讀取爲文本 //第二個參數爲編碼方式,默認爲utf-8
readAsDataURL file 將文件讀取爲DataURL //該方法事實上以一種特殊格式的URL地址形式直接讀入頁面(圖片,html)
abort none 中斷讀取
4、例子
<script type="text/javascript"> var result = document.getElementById("result"); var file = document.getElementById("file");
//判斷是否支持FileReader if(typeof FileReader=='undefined') { result.innerHTML = "<p> your browser not support the FileReader </p>" file.setAttribute('disabled','disabled'); } function readAsBinaryString() { var file = document.getElementById("file").file[0]; var reader = new FileReader(); reader.readAsBinaryString(file); reader.onload = function(f) { var result = document.getElementById("result"); result.innerHTML = this.result; } } </script>