How to get a File() or Blob() from an URL in javascript?

邮差的信 提交于 2019-12-03 05:31:58

Try using the fetch API. You can use it like so:

fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
  .then(res => res.blob()) // Gets the response and returns it as a blob
  .then(blob => {
    // Here's where you get access to the blob
    // And you can use it for whatever you want
    // Like calling ref().put(blob)

    // Here, I use it to make an image appear on the page
    let objectURL = URL.createObjectURL(blob);
    let myImage = new Image();
    myImage.src = objectURL;
    document.getElementById('myImg').appendChild(myImage)
});
<div id="myImg"></div>

As of August 2019, the fetch API has about 93% browser support worldwide, with basically just IE missing it. You can get that to near 100% using a polyfill, which I recommend if you're still targeting IE.

@James answer is correct but it is not compatible with all browsers. You can try

$.get('blob:yourbloburl').then(function(data) {
  var blob = new Blob([data], { type: 'audio/wav' });
});
stanimirsp

It did not work until I added credentials

fetch(url, {
      headers: {
        "Content-Type": "application/octet-stream",
      },
      credentials: 'include'
 })
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!