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

Viewed 95064

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

5 Answers

It did not work until I added credentials

fetch(url, {
      headers: {
        "Content-Type": "application/octet-stream",
      },
      credentials: 'include'
 })
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);
  }
}

If you are using homepage in package.json then ypu have to use:

CurrentUrl: http://localhost:3008/tempAppHomepageFromPackageJson/

const file: File = this.state.file;
const localUrlToFile = URL.createObjectURL(file);
const fileHash = localUrlToFile.split('/');
const objectUrl = location.href + fileHash[fileHash.length - 1];

objectUrl is the local url to file. For example to show in runtime you uploading file.

Second solution is (if you have no homepage in package.json):

const file: File = this.state.file;
const objectUrl = window.URL.createObjectURL(file);

Third solution (Not working in safari):

const file: File = this.state.file;
let reader = new FileReader();
reader.readAsDataURL(file);
const objectUrl = reader.result as string;

Enjoy ;)

Related