Categories
JavaScript Answers

How to convert a blob to a base64 string with JavaScript?

Spread the love

To convert a blob to a base64 string with JavaScript, we can use the FileReader instance’s readAsDataURL method.

For instance, we write:

const imageUrl = "https://picsum.photos/200/300";

const reader = new FileReader();
reader.onloadend = () => {
  const base64data = reader.result;                
  console.log(base64data);
}

(async () => {
  const response = await fetch(imageUrl)
  const imageBlob = await response.blob()
  reader.readAsDataURL(imageBlob);  
})()

We create the FileReader instance and set the onloadend property to a function that gets the base64 string from reader.result.

Next, we call fetch with the imageUrl to make a GET request to the image URL.

Then we call response.blob to return a promise with the image blob object.

Finally, we call readAsDataURL with imageBlob to read it into a base64 string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *