先介绍一下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);
};