1

I am trying to get the file object of an image stored in my websites folder. The image is already stored in the website and their is no need for "input type = "file"". This is what I have so far

         var file = new File([""], "../writeto/image.png", {
                             type: "png",
                        })

         console.log(file);

This code just creates an empty file object without an actual file in it. Is there a way to insert the image file into the object

developer
  • 15
  • 4
  • 1
    Have you tried: `var file = new Image(); file.src = "../writeto/image.png"`? Or if you really need a `File()` object, have you read https://stackoverflow.com/questions/25046301/convert-url-to-file-or-blob-for-filereader-readasdataurl – kmoser May 04 '20 at 19:44
  • @kmoser I did read the link you posted but everytime i tried it, it gave me an error. "TypeError: Failed to construct 'File': 2 arguments required, but only 0 present." – developer May 04 '20 at 19:53

1 Answers1

1

You can't just create a "file" from an URL. What you can do is request the file via XHR.

Here is a nicely wrapped function which you can re-use. You can modify it if you want it modify it to accept filename, filetypes etc.

function getImageFileFromUrl(url){
  let response = await fetch(url);
  let data = await response.blob();
  let metadata = {
    type: "image/jpeg"
  };
  return new File([data], "result.jpg", metadata);
}
const file = getImageFileFromUrl("url/image.jpg", "image/jpeg");
Salmin Skenderovic
  • 1,750
  • 9
  • 22
  • thanks, it worked. I just had to remove the await function on the const file. So it would be const file = getImageFileFromUrl("url/image.jpg", "image/jpeg"); – developer May 04 '20 at 20:49