图片二进制地址blob转化file对象

618 阅读1分钟

有一些场景就是Blob临时路径图片,需要转为file对象才可以传给后端,使用方式如下:

函数代码

function httpRequest(src) {
    return new Promise((resolve, reject) => {
      let xhr = new XMLHttpRequest();
      xhr.open('GET', src, true);
      xhr.responseType = 'blob';
      xhr.onload = function (e) {
        if (this.status == 200) {
          let myBlob = this.response;
          let files = new window.File([myBlob], myBlob.type, { type: myBlob.type }) // myBlob.type 自定义文件名
          resolve(files)
        } else {
          reject(false)
        }
      };
      xhr.send();
    })
  }

使用方式

httpRequest(bloburl) //bloburl 格式 blob:null/73e6954e-58ee-4165-870b-03614f9e3b5f