A virtual teacher who reveals to you the great secrets of Base64

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.

  • Nicole_80,
    How can I read this
    :|���P�5�...�}4�n������&[�� [
    • Administrator,
      Your string is not a Base64 value, but rather, it looks like binary data. I can’t help you, because by posting it here, many characters have been discarded.
  • May,
    Please help me read this
    • Administrator,
      What exactly are you trying to read?
  • Petri,
    Hi!

    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.
    • Administrator,
      Hello Petri!
      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.
  • Jefté,
    I am Brazilian and I have difficulties navigating the site (I do not speak English, I use Google translator).

    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?
  • ankitha,
    how can i handle No 'Access-Control-Allow-Origin' header is present on the requested resource . error?
  • nqhXncMU,
    0"XOR(if(now()=sysdate(),sleep(15),0))XOR"Z
  • nqhXncMU,
    -5) OR 689=(SELECT 689 FROM PG_SLEEP(15))--
  • nqhXncMU,
    -5) OR 754=(SELECT 754 FROM PG_SLEEP(15))--
  • gBqsPxAZ,
    -1)) OR 73=(SELECT 73 FROM PG_SLEEP(15))--
  • ncMUFCMU,
    KznOta6h') OR 262=(SELECT 262 FROM PG_SLEEP(15))--
Add new comment

If you have any questions, remarks, need help, or just like this page, please feel free to let me know by leaving a comment using the form bellow.
I will be happy to read every comment and, if necessary, I will do my best to respond as quickly as possible. Of course, spammers are welcome only as readers.