h5如何上传文件二进制流_FileReader H5上传文件

~~~

/**

*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();

~~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值