DEV Community

Discussion on: Convert a File URL/File to a Base64 string or DataURL using JavaScript

Collapse
 
loucyx profile image
Lou Cyx

You could use fetch instead of XMLHttpRequest, and instead of having a callback you can just make use of promises, like this:

const toDataURL = url =>
    fetch(url)
        .then(response => response.blob())
        .then(
            blob =>
                new Promise((resolve, reject) =>
                    Object.assign(new FileReader(), {
                        onloadend: ({ target }) => resolve(target.result),
                        onerror: ({ target }) => reject(target.error),
                    }).readAsDataURL(blob),
                ),
        );
Enter fullscreen mode Exit fullscreen mode

And then you use it like this:

toDataURL("https://Gurimg.sh20raj.repl.co/logo.jpg")
    .then(console.log)
    .catch(console.error);
Enter fullscreen mode Exit fullscreen mode

Consider that CORS is a factor here, so with either method you file fetching might get blocked unless your origin is allowed.

Cheers!

Collapse
 
sh20raj profile image
Sh Raj

Nice πŸ”†
And we have WebScrapperJS to pass cors...