Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

225
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda