Search code examples
javascriptaxiosfetchform-data

Attach an image from url in form data in JS?


I am trying to make a POST request where an image file is required as part of the payload. If I had the file itself I could have used it as part of the FormData. But the problem is that the client only has the image url. Is it possible to retrieve the image from the url and attach it as part of the FormData?


Solution

  • Use the fetch API to download the image.

    This will require the host of the image to grant you permission to access it using CORS.

    Get a blob() from the fetch response.

    Attach it to your FormData as if it were a file.


    It is quite likely, especially if you don't have the co-operation of the person hosting the image, that it would be simpler to change the API you are making the POST request to so it can accept a URL instead of an image file. You can then use server side code to make the request.