Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
How do I load an image from an URL (that has a different origin) into a File object?

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;
    })
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda