Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!