Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I try to upload an image to the Firebase storage from an URL (with ref().put(file))(www.example.com/img.jpg).

To do so i need a File or Blob, but whenever I try new File(url) it says "not enough arguments“…

EDIT: And I actually want to upload a whole directory of files, that’s why i can’t upload them via Console

like image 792
Sam Avatar asked May 19 '17 12:05

Sam


4 Answers

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 July 2022, the fetch API has about 97% 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.

like image 64
James Kraus Avatar answered Oct 15 '22 01:10

James Kraus


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

$.get('blob:yourbloburl').then(function(data) {
  var blob = new Blob([data], { type: 'audio/wav' });
});
like image 29
Ruan Carlos Avatar answered Oct 15 '22 01:10

Ruan Carlos


It did not work until I added credentials

fetch(url, {
      headers: {
        "Content-Type": "application/octet-stream",
      },
      credentials: 'include'
 })
like image 1
stanimirsp Avatar answered Oct 15 '22 02:10

stanimirsp


async function url2blob(url) {
  try {
    const data = await fetch(url);
    const blob = await data.blob();
    await navigator.clipboard.write([
      new ClipboardItem({
        [blob.type]: blob
      })
    ]);
    console.log("Success.");
  } catch (err) {
    console.error(err.name, err.message);
  }
}
like image 1
Stéphane Laurent Avatar answered Oct 15 '22 00:10

Stéphane Laurent