Home > other >  How do I load an image from an URL (that has a different origin) into a File object?
How do I load an image from an URL (that has a different origin) into a File object?

Time:09-21

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

CodePudding user response:

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

  • Related