H5新特性FileReader使用心得

H5 FileReader API 实战
本文介绍了HTML5中FileReader API的基本用法及其事件处理,包括如何读取文件为二进制、DataURL编码等,并通过具体示例展示了如何实现文件上传及图片预览功能。

先介绍一下H5中FileReader的一些方法以及事件

FileReader方法

名称作用
about()终止读取
readAsBinaryString(file)将文件读取为二进制编码
readAsDataURL(file)将文件读取为DataURL编码
readAsText(file, [encoding])将文件读取为文本
readAsArrayBuffer(file)​​​​​​​将文件读取为arraybuffer

FileReader事件

名称作用
onloadstart读取开始时触发
onprogress读取中
onloadend读取完成触发,无论成功或失败
onload文件读取成功完成时触发
onabort中断时触发
onerror出错时触发


我本次用作文件上传和图片预览两个功能

实际使用代码如下:

            this.reader = new FileReader();
            // Read in the image file as a binary string.
            this.reader.onloadstart = function(e) {};
            this.reader.onload = function(e) {};
            this.reader.onloadend = function(e) {
                if (e.target.readyState == FileReader.DONE) { // DONE == 2
                    var loaded = e.loaded;
                    that.upload(f.name, e.target.result, total, i,
                    });
                }
            };
            this.reader.onerror = function(e) {
                that.errorHandler(e, that);
            };
            this.reader.onprogress = function(e) {
                that.updateProgress(e,progressBar);
            };
            this.reader.onabort = function(e) {
                that.setStatus(0, "文件上传取消");
            };

            this.reader.readAsArrayBuffer(f);



Editor.prototype.upload = function(flag,nm, r, t, onSuccess) {
var blob = new Blob([ r ]);
var type = "";
if (flag) {
this.box.className = "hide";
this.img.src = URL.createObjectURL(blob);//图片的预览
this.img.className = "show";
type = "license";
} else {
this.box2.className = "hide";
this.img2.src = URL.createObjectURL(blob);
this.img2.className = "show";
type = "idcard";
}


var fd = new FormData();
fd.append('file', blob);
fd.append('fname', encodeURI(nm));
fd.append('flen', t);
fd.append('oid', this.options.ownerId);
fd.append('type', type);
fd.append('fid', this.options.id);
var xhr = new XMLHttpRequest();
xhr.open('post', omservices.uploadapi(0), true);
var that = this;
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
if (onSuccess) {
onSuccess(data.fid);
}
}
}
xhr.send(fd);
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值