image url to file() object using js
Asked Answered
B

3

14

For a registration module in my vue app I let users upload images in a form. I upload these images to my storage and save the download url of this photo in the registration. When editing a registration I need to get the photo's out of the storage which is simple since I got the url. But I need it to be a file() object. I have found ways to turn it into a blob but it needs to be a file. How can I do this?

Barthel answered 4/3, 2019 at 12:46 Comment(1)
did you manage to solve this? i'm facing a similar problem in reactMarrakech
G
35

It can be done by requesting a blob and generating a File object. It is necessary to specify the MIME type of the blob.

const urlToObject= async()=> {
  const response = await fetch(image);
  // here image is url/location of image
  const blob = await response.blob();
  const file = new File([blob], 'image.jpg', {type: blob.type});
  console.log(file);
}
Gourde answered 16/5, 2020 at 17:0 Comment(2)
The problem with this solution is that you can get blocked by CORS policy when fetching the image.Robrobaina
Draw an Image element then convert to file hacksoft.io/blog/handle-images-cors-error-in-chrome then developer.mozilla.org/en-US/docs/Web/HTTP/CORSSear
S
3

The ES6 way, with Promise:

const blobUrlToFile = (blobUrl:string): Promise<File> => new Promise((resolve) => {
    fetch(blobUrl).then((res) => {
      res.blob().then((blob) => {
        // please change the file.extension with something more meaningful
        // or create a utility function to parse from URL
        const file = new File([blob], 'file.extension', {type: blob.type})
        resolve(file)
      })
    })
  })
Soosoochow answered 18/11, 2021 at 4:7 Comment(0)
S
0

Since you are letting the user upload a file, you already have the file as a File object.

But if you wanna convert it to a blob for making some edits and convert it back to a File object, you can use the File() constructor for converting a blob to a File.

const file = new File([blob], "imagename.png");

Also, notice that the File() constructor takes an array of blobs as argument and not a single blob.

Seraphina answered 4/3, 2019 at 13:52 Comment(1)
I do not since the upload is in an other module. I am getting the data from the database and thus any local items including the file is gone. I don't need it to ever be a blob. I guess It could be a workaround to change the url into an blob and then the blob into an file but I imagine there be a more straight forward way.Barthel

© 2022 - 2024 — McMap. All rights reserved.