Convert Blob to Base64 and Vice Versa in JavaScript

In web development, handling binary data is a common task, especially when dealing with files, images, or other media. JavaScript provides ways to convert between Blob objects and Base64 strings, which is useful for tasks like uploading files, displaying images, or transmitting data over APIs. In this blog post, we’ll explore how to convert a Blob to a Base64 string and vice versa in JavaScript, with clear examples and practical use cases.

What is a Blob?

A Blob (Binary Large Object) is an object in JavaScript that represents raw binary data. It’s commonly used to handle files, such as images, PDFs, or other binary formats, in web applications. Blobs are immutable and can be created from arrays, strings, or other data types.

What is Base64?

Base64 is a method for encoding binary data into an ASCII string format. It’s widely used to embed binary data, like images, directly into text-based formats such as JSON, HTML, or CSS. Base64 strings are safe for transmission over text-based protocols but are approximately 33% larger than the original binary data.

Why Convert Between Blob and Base64?

Let’s dive into the code to see how these conversions work.

Converting Blob to Base64

To convert a Blob to a Base64 string, you can use the FileReader API or modern async methods like Blob.text() with btoa(). Here’s how to do it:

Using FileReader

The FileReader API allows you to read the contents of a Blob and convert it to a Base64 string.

async function blobToBase64(blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result.split(',')[1]); // Extract Base64 part
    reader.onerror = reject;
    reader.readAsDataURL(blob);
  });
}

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

blobToBase64(blob).then(base64 => {
  console.log("Base64:", base64); // Output: SGVsbG8sIFdvcmxkIQ==
});

Explanation:

Using Blob.text() and btoa()

For text-based Blobs, you can use Blob.text() combined with btoa():

async function blobToBase64(blob) {
  const text = await blob.text();
  return btoa(text);
}

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

blobToBase64(blob).then(base64 => {
  console.log("Base64:", base64); // Output: SGVsbG8sIFdvcmxkIQ==
});

Note: This method works well for text-based Blobs but may not handle binary data (e.g., images) correctly due to encoding issues. For binary data, use FileReader.

Converting Base64 to Blob

To convert a Base64 string back to a Blob, you can decode the Base64 string and create a new Blob object. Here’s how:

Using atob() and Blob

The atob() function decodes a Base64 string into binary data, which can then be used to create a Blob.

function base64ToBlob(base64, mimeType = '') {
  const binary = atob(base64);
  const array = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) {
    array[i] = binary.charCodeAt(i);
  }
  return new Blob([array], { type: mimeType });
}

// Example usage
const base64 = "SGVsbG8sIFdvcmxkIQ=="; // Base64 for "Hello, World!"
const blob = base64ToBlob(base64, "text/plain");

console.log(blob); // Blob { size: 13, type: "text/plain" }

Explanation:

Practical Example: Displaying an Image

Let’s combine both conversions to handle an image file. Suppose you have an image input that you want to convert to Base64 for display and then convert it back to a Blob for further processing (e.g., uploading).

// HTML: <input type="file" id="imageInput" accept="image/*">
const input = document.getElementById("imageInput");

input.addEventListener("change", async () => {
  const file = input.files[0];
  const blob = new Blob([file], { type: file.type });

  // Convert Blob to Base64
  const base64 = await blobToBase64(blob);
  console.log("Base64:", base64);

  // Display image using Base64
  const img = document.createElement("img");
  img.src = `data:${file.type};base64,${base64}`;
  document.body.appendChild(img);

  // Convert Base64 back to Blob
  const newBlob = base64ToBlob(base64, file.type);
  console.log("Blob:", newBlob);
});

Explanation:

Use Cases

  1. File Uploads: Convert files to Base64 to send them as part of a JSON payload to an API.
  2. Image Previews: Display images in the browser without uploading them to a server.
  3. Data URLs: Embed small images or files directly in HTML or CSS using data: URLs.
  4. API Responses: Convert Base64-encoded data from APIs into Blobs for downloading or processing.

Best Practices

Conclusion

Converting between Blob and Base64 in JavaScript is straightforward with the right tools, such as FileReader, btoa(), and atob(). Whether you’re embedding images in a webpage, sending files to an API, or processing binary data, these techniques are essential for modern web development. By following the examples above, you can efficiently handle binary data in your JavaScript applications.

For more advanced use cases, consider exploring libraries like axios for API interactions or FileSaver.js for saving Blobs as files. Happy coding!

Latest blog posts

Explore the world of programming and cybersecurity through our curated collection of blog posts. From cutting-edge coding trends to the latest cyber threats and defense strategies, we've got you covered.