最近項目開發(fā)中涉及到文件上傳功能,使用的是七牛的服務(wù)。查看七牛文檔發(fā)現(xiàn)文件上傳格式為blob,而本地添加上傳文件時獲取到的是file格式,因此需要將file轉(zhuǎn)換為blob,具體轉(zhuǎn)換方法如下:
// html
<input type="file" onchange="fileChange()" />
//script
function fileChange() {
? let e = e || window.event;
? let file = e.target.files[0];
? let reader = new FileReader();
? let rs = reader.readAsArrayBuffer(file);
? let blob = null;
? reader.onload = (e) => {
? ? if (typeof e.target.result === 'object') {
? ? ? blob = new Blob([e.target.result])
? ? } else {
? ? ? blob = e.target.result
? ? }
? ? console.log(Object.prototype.toString.call(blob));
? }
}