Ask any question about JavaScript here... and get an instant response.
How can I convert a Blob to a base64 string in JavaScript for uploading to a server?
Asked on Nov 16, 2025
Answer
To convert a Blob to a base64 string in JavaScript, you can use the FileReader API. This allows you to read the Blob's data as a base64-encoded string, which is useful for uploading to a server.
<!-- BEGIN COPY / PASTE -->
function blobToBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result.split(",")[1]);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
}
// Example usage:
const blob = new Blob(["Hello, world!"], { type: "text/plain" });
blobToBase64(blob).then(base64String => {
console.log(base64String); // Outputs the base64 string
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "blobToBase64" function returns a Promise that resolves with the base64 string.
- "FileReader.readAsDataURL" reads the Blob and triggers the "onloadend" event when done.
- "reader.result" contains the base64 data URL; "split(',')[1]" extracts the base64 part.
- Always handle errors with "reader.onerror" to ensure robustness.
Recommended Links:
