'Is there any way in JavaScript, to convert image source url to file such that it can be accepted in input of type file or by API endpoint?

It's easy to change file type input to image source url for preview.. but.. Considering a scenario where you're trying to edit a blog, so you fetch a blog and fill the input fields based on the data received. Everything works fine.. but how do you handle image input? We receive image url as image source but how can we use that image url to fill up image input of file type? enter image description here

I tried looking to this: https://stackoverflow.com/questions/50537735/convert-blob-to-image-file/50538148#:~:text=getContext(%222d%22)%3B%20%2F%2F,file%20in%20the%20base64%20format. but couldn't understand well.

#Solved for my use case: There was a mistake on my side, I assumed if the user doesn't selects an image, it'll will make the image field empty and hence putting null value in the database. I figured out that, it's not like what I've thought.



Solution 1:[1]

It can be done with the help of fetch library like this :-

const imageSrcURLToFile = async (image_url) =>{
   const image = await fetch(image_url);
   const blob = await image.blob();
   const url = URL.createObjectURL(blob);
   const link = document.createElement('a')
   link.href = url;
   link.download = 'image file name here'
   document.body.appendChild(link)
   link.click()
   document.body.removeChild(link)
}

for more information checkout this article :- https://dev.to/sbodi10/download-images-using-javascript-51a9

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aamir Khan