Explain Codes LogoExplain Codes Logo

Convert blob to base64

javascript
async-programming
blob-conversion
base64
Alex KataevbyAlex Kataev·Jan 7, 2025
TLDR

To convert a Blob to Base64 with JavaScript, use the FileReader's readAsDataURL and extract the Base64 sequence from the result upon the triggering of the onload event.

const toBase64 = blob => new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result.split(',')[1]); reader.onerror = reject; reader.readAsDataURL(blob); }); // Usage: const blob = new Blob(['content'], { type: 'text/plain' }); toBase64(blob).then(console.log); // Logs the Base64 string output

Deep dive: Understanding advanced cases and edge scenarios

Asynchronicity and Promises

JavaScript typically handles Blobs within asynchronous contexts. So, we wrap our conversion logic with a Promise to manage the asynchrony reliably. Here, we handle the onloadend event that indicates the completion of the Blob read process.

async function convertBlobToBase64(blob) { const reader = new FileReader(); const dataPromise = new Promise((resolve, reject) => { reader.onloadend = () => resolve(reader.result); // Yeah! Blob read success 🎉 reader.onerror = reject; // Oops! Something went wrong 😢 }); reader.readAsDataURL(blob); return await dataPromise; // Awaits the promise and returns the result }

This async function can now be awaited or chained with .then() to effectively handle success and failure cases.

Binary handling and UTF-8

readAsDataURL handles character encoding internally which comes in handy when dealing with binary or non-text data. This makes it a safer alternative to btoa, which could mess up multi-byte characters.

Conversion during fetching

The Fetch API can play together well with our Base64 conversion logic. Let's fetch an image and convert it to Base64 simultaneously:

(async () => { const response = await fetch('path/to/your/image.png'); const blob = await response.blob(); // Blob received 📦 const base64 = await convertBlobToBase64(blob); // Voila! Our Base64 string is ready 🥳 console.log(base64); })();

Advanced methods: Tricks, caveats, and prospects

The Response and btoa() method

Want to take an alternate route? Consider the Response constructor and btoa() function. But remember, with great power comes great responsibility:

async function blobToBase64(blob) { const data = await new Response(blob).text(); return btoa(data); // It won't bite; unless misused! 😁 }

Staying on top of the game

Keep yourself updated with latest APIs and spec improvements. JavaScript is an evolving language; there might be an even better method just around the corner.

Picking the best tool

Remember, different problems require different solutions. Having a combined knowledge of various approaches will make you a Swiss army knife of Blob to Base64 conversion.