How can I convert a blob to a base64 string in JavaScript?
Richard W
richard w profile pic

To convert a Blob object to a Base64 string in JavaScript, you can use the FileReader API. Here's a step-by-step guide on how to achieve this: 1. Obtain the Blob object: Assuming you have a Blob object, either from an API response or user input, ensure that you have a reference to it. For example:

1
2
3

   const blob = new Blob(['Hello, World!'], { type: 'text/plain' });
   

Replacenew Blob(['Hello, World!'], { type: 'text/plain' }) with your actual Blob object. 2. Create a FileReader object: Use the FileReader constructor to create a new FileReader instance.

1
2
3

   const reader = new FileReader();
   

3. Handle the FileReader's load event: Add an event listener to the FileReader instance to handle theload event. This event is fired when the file is successfully loaded.

1
2
3
4
5

   reader.addEventListener('load', () => {
     // Code to handle the loaded data
   });
   

Inside the event listener, you will handle the loaded data. 4. Read the Blob data: Use thereadAsDataURL() method of the FileReader instance to read the Blob data as a Data URL, which contains the Base64-encoded representation of the Blob.

1
2
3

   reader.readAsDataURL(blob);
   

ThereadAsDataURL() method starts reading the Blob data asynchronously. 5. Retrieve the Base64 data: Inside the event listener for theload event, you can access the Base64-encoded data using theresult property of the FileReader instance.

1
2
3
4
5
6

   reader.addEventListener('load', () => {
     const base64String = reader.result;
     console.log(base64String);
   });
   

Thebase64String variable contains the Base64-encoded string representation of the Blob. 6. Handle any errors: It's a good practice to handle potential errors by listening for theerror event on the FileReader instance.

1
2
3
4
5

   reader.addEventListener('error', (error) => {
     console.error('Error occurred while reading the Blob:', error);
   });
   

In the event listener for theerror event, you can handle or log any error that occurred during the reading process. By following these steps, you can convert a Blob object to a Base64 string in JavaScript using the FileReader API. Adjust the code as needed to fit your specific use case and handle any additional error handling or data manipulation requirements.