FileReader對象採用異步方式讀取文件,在不一樣的讀取階段會觸發不一樣的事件。html
事件列表:異步
(1).abort事件:讀取中斷或調用reader.abort()方法時觸發。this
(2).error事件:讀取出錯時觸發。spa
(3).load事件:讀取成功後觸發。code
(4).loadend事件:讀取完成後觸發,不論是否成功。觸發順序排在 onload 或 onerror 後面。orm
(5).loadstart事件:讀取將要開始時觸發。htm
(6).progress事件:讀取過程當中週期性觸發。對象
代碼實例:blog
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
|
<!DOCTYPE html>
<
html
lang
=
"zh-cn"
>
<
head
>
<
meta
charset
=
" utf-8"
>
<
title
>螞蟻部落</
title
>
<
script
>
var h = {
init: function () {
var _this = this;
document.getElementById("File").onchange = _this.fileHandler;
document.getElementById("Abort").onclick = _this.abortHandler;
_this.status = document.getElementById("Status");
_this.progress = document.getElementById("Progress");
_this.percent = document.getElementById("Percent");
_this.loaded = 0;
//每次讀取1M
_this.step = 1024 * 1024;
_this.times = 0;
},
fileHandler: function (e) {
var _this = h;
_this.file = this.files[0];
_this.reader = new FileReader();
_this.total = _this.file.size;
_this.reader.onloadstart = _this.onLoadStart;
_this.reader.onprogress = _this.onProgress;
_this.reader.onabort = _this.onAbort;
_this.reader.onerror = _this.onerror;
_this.reader.onload = _this.onLoad;
_this.reader.onloadend = _this.onLoadEnd;
//讀取第一塊
_this.readBlob(0);
},
readBlob: function (start) {
var _this = h;
var blob,
file = _this.file;
_this.times += 1;
blob = file.slice(start, start + _this.step + 1);
_this.reader.readAsText(blob);
},
onLoadStart: function () {
console.log("讀取將要開始");
var _this = h;
},
onProgress: function (e) {
console.log("正在進行讀取");
var _this = h;
_this.loaded += e.loaded;
//更新進度條
_this.progress.value = (_this.loaded / _this.total) * 100;
},
onAbort: function () {
console.log("讀取中斷");
var _this = h;
},
onError: function () {
console.log("讀取中斷");
var _this = h;
},
onLoad: function () {
console.log("讀取完成");
var _this = h;
if (_this.loaded <
_this.total
) {
_this.readBlob(_this.loaded);
} else {
_this.loaded
= _this.total;
}
},
onLoadEnd: function () {
console.log("讀取結束");
var
_this
= h;
},
abortHandler: function () {
var
_this
= h;
if (_this.reader) {
_this.reader.abort();
}
}
};
window.onload
=
function
() {
h.init();
}
</script>
</
head
>
<
body
>
<
form
>
<
fieldset
>
<
legend
>分度讀取文件:</
legend
>
<
input
type
=
"file"
id
=
"File"
/>
<
input
type
=
"button"
value
=
"中斷"
id
=
"Abort"
/>
<
p
>
<
label
>讀取進度:</
label
>
<
progress
id
=
"Progress"
value
=
"0"
max
=
"100"
></
progress
>
</
p
>
<
p
id
=
"Status"
></
p
>
</
fieldset
>
</
form
>
</
body
>
</
html
>
|
上面是一個完整的演示代碼,讀取較大的文件演示效果更佳明顯,文件是分段上傳的。事件
控制檯截圖以下: