0

At first I thought it should be as easy as:

const img = document.createElement('img');
img.onload = () => { ... }
img.onerror = () => { ... }
img.src = url;

But then it turned out I need to draw it on a canvas, then toBlob(). And don't forget to add CORS and crossorigin="anonymous" to the img tag. Isn't it a bit too involved? Is there a better way?

To show you the final solution (you need CORS headers):

function getFileFromURL(url) {
    return new Promise((resolve, reject) => {
        const fileName = url.split('/').pop();
        const img = document.createElement('img');
        img.setAttribute('crossorigin', 'anonymous');
        img.onload = () => {
            const canvas = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0);
            canvas.toBlob(blob => {
                resolve(new File([blob], fileName));
            });
        };
        img.onerror = () => {
            reject('something went wrong');
        };
        img.src = url;
    })
}
15
  • Well you could request the actual image data using AJAX ... but then you won't get away with crossorigin="anonymous" any more, the remote party would have to actively support proper CORS then.
    – CBroe
    Sep 17, 2021 at 14:51
  • if you just want to display an image, cors shouldnt be an issue, but if you are trying to access the data of the image, like scanning pixels etc. Do you have an example?
    – Skarlinski
    Sep 17, 2021 at 14:51
  • @CBroe With my solution I also need to add CORS. Without them it doesn't work.
    – x-yuri
    Sep 17, 2021 at 14:52
  • @Skarlinski I need to access the data.
    – x-yuri
    Sep 17, 2021 at 14:52
  • 1
    "Is there a better way?" Yes, it's called Code Review Stack Exchange.
    – Rojo
    Sep 17, 2021 at 15:06

1 Answer 1

0

The solution suggested by CBroe is arguably better:

function getFileFromURL(url) {
    const fileName = url.split('/').pop();
    return fetch(url)
        .then(response => {
            return new File([response.data], fileName);
        });
}

Make sure you add CORS headers to the request(s).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.