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

Encode Blob to Base64 in JavaScript

To encode a Blob object to Base64 in JavaScript you can use the FileReader.readAsDataURL() method. Below I provide a simple example which is supported by most popular browsers (Chrome 6+, Edge 12+, Firefox 3.6+, Internet Explorer 10+, Safari 6+).

// Create the Blob object (of course, it can be of any type and defined in any way)
var blob = new Blob(['Welcome to <b>base64.guru</b>!'], {type: 'text/html'});

// Define the FileReader which is able to read the contents of Blob
var reader = new FileReader();

// The magic always begins after the Blob is successfully loaded
reader.onload = function () {
  // Since it contains the Data URI, we should remove the prefix and keep only Base64 string
  var b64 = reader.result.replace(/^data:.+;base64,/, '');
  console.log(b64); //-> "V2VsY29tZSB0byA8Yj5iYXNlNjQuZ3VydTwvYj4h"

  // Decode the Base64 string and show result just to make sure that everything is OK
  var html = atob(b64);
  console.log(html); //-> "Welcome to <b>base64.guru</b>!"

// Since everything is set up, let’s read the Blob and store the result as Data URI

Another way to convert Blob to Base64 is to call reader.readAsBinaryString(blob) and use btoa(reader.result) to get the Base64 string. However, this method will most likely work slower and is not supported by Internet Explorer at all.

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.