Sometimes, we want to convert a blob to a base64 string with JavaScript.
In this article, we’ll look at how to convert a blob to a base64 string with JavaScript.
How to convert a blob to a base64 string with JavaScript?
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.
Conclusion
To convert a blob to a base64 string with JavaScript, we can use the FileReader instance’s readAsDataURL method.