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?
- Blob to Base64: Useful for embedding binary data in JSON, displaying images in
<img>
tags using data URLs, or sending files over APIs that require text-based formats. - Base64 to Blob: Useful for reconstructing binary data from Base64 strings, such as when receiving encoded data from an API or preparing a file for download.
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:
FileReader.readAsDataURL
reads theBlob
and returns a data URL (e.g.,data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==
).- We split the result by
,
to extract the Base64-encoded part. - The function returns a
Promise
to handle the asynchronous nature ofFileReader
.
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:
atob(base64)
decodes the Base64 string into a binary string.- We convert the binary string into a
Uint8Array
to represent the bytes. - A new
Blob
is created with theUint8Array
and an optional MIME type.
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:
- The image file from the input is converted to a
Blob
. - The
Blob
is converted to a Base64 string for display in an<img>
tag. - The Base64 string is converted back to a
Blob
for further processing.
Use Cases
- File Uploads: Convert files to Base64 to send them as part of a JSON payload to an API.
- Image Previews: Display images in the browser without uploading them to a server.
- Data URLs: Embed small images or files directly in HTML or CSS using
data:
URLs. - API Responses: Convert Base64-encoded data from APIs into Blobs for downloading or processing.
Best Practices
- Use FileReader for Binary Data: For non-text data like images or PDFs,
FileReader
is more reliable thanbtoa()
. - Specify MIME Types: Always provide the correct MIME type when creating a
Blob
to ensure proper handling. - Handle Large Files Carefully: Converting large files to Base64 can be memory-intensive, so consider alternatives like streaming for large datasets.
- Error Handling: Always include error handling in async operations to manage invalid Base64 strings or file reading errors.
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.