file对象和blob对象的互相转换

1,804 阅读1分钟

最近项目开发中涉及到文件上传功能,使用的是七牛的服务。查看七牛文档发现文件上传格式为blob,而本地添加上传文件时获取到的是file格式,因此需要将file转换为blob,记录一下file对象和blob对象的互相转换。

1.file转blob对象

fileToBlob(file){
    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));
    }
}

2.blob转file

let files = new window.File([this.blob], file.name, {type: file.type})