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);

// Send HTTP request and fetch file as ArrayBuffer
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';

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 (4)

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?
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.