~~~
/**
*FileReader.js
**属性
*files[0] : 获取file文件的所有信息
*loaded : 每次读取的文件大小
*size : 读取文件的总大小
**方法
*slice(start, end, 编码) : 分块读取
*readAsBinaryString(files[0]) : 将文件读取成二进制数据
*readAsDataURL(files[0]) : 将文件读取成URL 图片预览使用该方法
*readAsText(files[0], 编码) : 将文件读取成文本 默认编码utf-8
*abort : 中断读取文件
**事件
*onloadstart : 开始读取文件时触发
*onprogress : 读取过程中触发
*onload : 读取成功后触发
*/
// 分段加载文件
var FileLoad = function (){
this.init();
};
FileLoad.prototype = {
init : function (){
// 创建FileReader实例
this.reader = new FileReader();
// 每次读取的大小
this.state = 1;
// 读取总大小
this.sumState = 0;
this.elFile = $('#File');
// files属性值
this.file;
this.addEvent(this.reader);
},
addEvent : function (reader){
var t = this;
// 读取文件
this.elFile.on('change', function (){
// files属性值
t.file = t.elFile[0].files[0];
t.readFile();
});
reader.onprogress = function (e){t.progress(e);}
// onload : 文件读取成功完成时触发
reader.onload = function (e){t.load(e);}
},
// 读取文件
readFile : function (){
// 每次读取一块文件
var fileData = this.file.slice(this.sumState, this.state+this.sumState, 'text/plain;charset=UTF-8');
// readAsDataURL(file节点.files[0]) : 将文件读取为 DataURL
this.reader.readAsBinaryString(fileData);
},
// 读取过程中触发
progress : function (e){
// 每读取一块以后 总量++
this.sumState += e.loaded;
// 设置进度条
$('progress').attr('value', this.sumState/this.file.size*100);
},
// 读取完成
load : function (e){
// loaded : 每次读取的大小
// size : 总大小
if(this.sumState < this.file.size){
this.readFile();
}
// 终端
// this.reader.abort();
}
};
new FileLoad();
// 图片预览
var FileImg = function (){
this.init();
};
FileImg.prototype = {
init : function (){
// 创建FileReader实例
this.reader = new FileReader();
this.elFile = $('#File2');
this.addEvent(this.reader);
},
addEvent : function (reader){
var t = this;
// 读取文件
this.elFile.on('change', function (){
// 读取文件
t.reader.readAsDataURL(t.elFile[0].files[0]);
});
// onload : 文件读取成功完成时触发
reader.onload = function (e){t.load(e);}
},
// 读取成功后触发
load : function (e){
$('body').append( $('').attr('src', e.target.result) );
}
};
new FileImg();
~~~