我允许用户通过拖放和其他方法将图像加载到页面中。当图像被删除时,我使用URL。createObjectURL转换为显示图像的对象URL。我没有撤销url,因为我重用了它。

因此,当需要创建一个FormData对象时我可以允许他们上传一个包含这些图像的表单,有什么方法可以将对象URL反向到Blob或File中,这样我就可以将它附加到FormData对象中?


当前回答

查看从XHR请求中获取BLOB数据,指出BlobBuilder在Chrome中不工作,所以你需要使用:

xhr.responseType = 'arraybuffer';

其他回答

如果你在画布中显示文件,你也可以将画布内容转换为blob对象。

canvas.toBlob(function(my_file){
  //.toBlob is only implemented in > FF18 but there is a polyfill 
  //for other browsers https://github.com/blueimp/JavaScript-Canvas-to-Blob
  var myBlob = (my_file);
})

查看从XHR请求中获取BLOB数据,指出BlobBuilder在Chrome中不工作,所以你需要使用:

xhr.responseType = 'arraybuffer';

按照@Kaiido的回答,另一种重载URL而不搞乱URL的方法是像这样扩展URL类:

export class URLwithStore extends URL {
  static createObjectURL(blob) {
    const url = super.createObjectURL(blob);
    URLwithStore.store = { ...(URLwithStore.store ?? {}), [url]: blob };
    return url;
  }

  static getFromObjectURL(url) {
    return (URLwithStore.store ?? {})[url] ?? null;
  }

  static revokeObjectURL(url) {
    super.revokeObjectURL(url);
    if (
      new URL(url).protocol === "blob:" &&
      URLwithStore.store &&
      url in URLwithStore.store
    )
      delete URLwithStore.store[url];
  }
}

使用

const blob = new Blob( ["foo"] );
const url = URLwithStore.createObjectURL( blob );
const retrieved = URLwithStore.getFromObjectURL( url );
console.log( "retrieved Blob is Same Object?", retrieved === blob );

正如gengkev在他的评论中提到的,看起来最好/唯一的方法是使用异步xhr2调用:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'blob:http%3A//your.blob.url.here', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
  if (this.status == 200) {
    var myBlob = this.response;
    // myBlob is now the blob that the object URL pointed to.
  }
};
xhr.send();

更新(2018):对于可以安全使用ES5的情况,Joe在下面给出了一个更简单的基于ES5的答案。

现代的解决方案:

let blob = await fetch(url).then(r => r.blob());

url可以是对象url,也可以是普通url。