Convert Blob Data to Base64 in JavaScript

Convert Blob Data to Base64 in JavaScript
convert blob to base64

Hi there!

Converting JavaScript file objects or blobs to Base64 strings can be useful, for example when we can only send string based data to the server. In this blog post, we’ll explore how to use JavaScript to generate a Base64 string and a DataURL from a file object.

Blob:

Blob is a fundamental data type in JavaScript. Blob stands for Binary Large Object and it is a representation of bytes of data. Web browsers support the Blob data type for holding data. Blob is the underlying data structure for the File object and the FileReader API. Blob has a specific size and file type just like ordinary files and it can be stored and retrieved from the system memory. Blob can also be converted and read as Buffers. Buffers are very handy to store binary data such as the binary data of an image or a file.

We convert Blob to Base64 encoded string. That encoding represents binary data as a string of ultra-safe “readable” characters with ASCII-codes from 0 to 64. And what’s more important – we can use this encoding in “data-urls”.

data url has the form data:[<mediatype>][;base64],<data>. We can use such urls everywhere, on par with “regular” urls.

For instance, here’s a smiley:

<img src="data:image/png;base64,R0lGODlhDAAMAKIFAF5LAP/zxAAAANyuAP/gaP///wAAAAAAACH5BAEAAAUALAAAAAAMAAwAAAMlWLPcGjDKFYi9lxKBOaGcF35DhWHamZUW0K4mAbiwWtuf0uxFAgA7">

The browser will decode the string and show the image.

To transform a Blob into base64, we’ll use the built-in FileReader object. It can read data from Blobs in multiple formats.

We cannot transfer Binary data over a Network in its raw format. This is because the raw bytes may be interpreted incorrectly due to the different protocols involved in the Network. There is also a higher chance of it being corrupted while being transferred over the Network. Hence this binary data is encoded into characters using Base64 encoding before being transferred over the network such as in email attachments, HTML form data, etc. Base64 encoding is a way of converting arbitrary Binary data into ASCII characters. Base64 encoding is used so that we do not have to rely on external files and scripts in web browsers.

FileReader:

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. FileReader can only access the contents of files that the user has explicitly selected, either using an HTML <input type="file"> element or by drag and drop. It cannot be used to read a file by pathname from the user's file system.

We will make use of FileReader.readAsDataURL() function which reads the contents of the specified Blob data type and will return a Base64 Encoded String with data: attribute when the read operation is finished and onload() is triggered if it is success or onerror().

The FileReader.onload(), handler for the load event. This event is triggered each time the reading operation is successfully completed.

The FileReader.onerror(), handler for the error event. This event is triggered each time the reading operation encounter an error.

Implementation:

We will make use of Promises and async/await as readAsDataURL() is async. Once the read operations is finished, return encoded data which is from reader.result.

const convertBlobToBase64 = async (blob) => { // blob data
  return await blobToBase64(blob);
}

const blobToBase64 = blob => new Promise((resolve, reject) => {
  const reader = new FileReader();
  reader.readAsDataURL(blob);
  reader.onload = () => resolve(reader.result);
  reader.onerror = error => reject(error);
});

Caller:

console.log(await convertBlobToBase64(someFileData)); // pass your blob/file info here

That's it, you have now learnt how to transform blob data to base64. Thanks for reading!