Encode remote file to Base64 in JavaScript
To encode a remote file on Base64 to Javascript, you must have its URL address, and if it is not a relative URL, make sure that CORS header “Access-Control-Allow-Origin” is not missing, otherwise you’ll face the “Cross-Origin Request Blocked” error.
Below I want to show you how to encode a remote image to Base64 (of course, it can be a file of any type, such as PDF or HTML). The example is supported by most popular browsers (Chrome 7+, Edge 12+, Firefox 4+, Internet Explorer 10+, Safari 5.1+).
// If you are loading file from a remote server, be sure to configure “Access-Control-Allow-Origin”
// For example, the following image can be loaded from anywhere
var url = '//static.base64.guru/uploads/images/1x1.gif';
// Initialize the XMLHttpRequest and wait until file is loaded
var xhr = new XMLHttpRequest();
xhr.onload = function () {
// Create a Uint8Array from ArrayBuffer
var codes = new Uint8Array(xhr.response);
// Get binary string from UTF-16 code units
var bin = String.fromCharCode.apply(null, codes);
// Convert binary to Base64
var b64 = btoa(bin);
console.log(b64); //-> "R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs="
};
// Send HTTP request and fetch file as ArrayBuffer
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.send();
Also, you can define responseType
as blob
and convert response to Base64 using FileReader
. For more info see how to Encode Blob to Base64. Perhaps this approach may be more efficient.
Comments (13)
I hope you enjoy this discussion. In any case, I ask you to join it.
:|���P�5�...�}4�n������&[�� [
Looks like what I'm after. But how to include “Access-Control-Allow-Origin”? Could you provide a code example where it's included? I'm getting the error you mentioned
[UPDATED: ]
I found this as a solution:
https://stackoverflow.com/questions/20920965/cross-origin-problems-getting-base64-encoding-of-an-image
using a proxy. But I'd be super glad if you could post an updated version of your code above that would accept any remote files from any domains without cross-origin issues <3 I thinki it would be faster and less of a hack than a 3rd party proxy that might have some usage limitations etc
I'll buy you a coffee for sure :)
Trying to make a javascript api call to determine image details using the haystack.ai API. Unlike everypixel.com API (https://api.everypixel.com) they don't seem to allow remote url, but you'll need to include image as BASE64 in the api call.
I'm a newbie.
Fortunately, browsers block HTTP requests to external websites and it's great that this cannot be bypassed. So there is no way to encode remote files on webpages if the remote server does not send a proper “Access-Control-Allow-Origin” header. Therefore you have to use a proxy or contact the owners of the remote server and ask them to set up CORS.
How to validate a base64 string?
I get the string on my website, but how do I validate it? How to check if the string is base64?