image url to file() object using js image url to file() object using js vue.js vue.js

image url to file() object using js


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);}


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.


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)      })    })  })