Creating a BLOB from a Base64 string in JavaScript
As a tech professional working with JavaScript, you may come across situations where you need to convert a Base64 string into a BLOB object. This can be useful when dealing with file uploads, data manipulation, or other scenarios where you need to work with binary data.
In this blog post, we will explore two different solutions to create a BLOB from a Base64 string in JavaScript.
Solution 1: Using the atob() and Uint8Array()
The first solution involves using the atob()
function to decode the Base64 string and then creating a Uint8Array()
from the decoded string. Finally, we can create a BLOB object using the Blob()
constructor.
const base64String = 'Your Base64 string here';
const decodedString = atob(base64String);
const byteArray = new Uint8Array(decodedString.length);
for (let i = 0; i < decodedString.length; i++) {
byteArray[i] = decodedString.charCodeAt(i);
}
const blob = new Blob([byteArray], { type: 'application/octet-stream' });
In the above code snippet, replace 'Your Base64 string here'
with your actual Base64 string. The resulting BLOB object will have the MIME type set to application/octet-stream
. You can modify the MIME type as per your requirements.
Solution 2: Using the fetch() API
The second solution utilizes the fetch()
API to convert the Base64 string into a BLOB object. This solution is more concise and doesn't require manual decoding of the string.
const base64String = 'Your Base64 string here';
const response = await fetch(`data:application/octet-stream;base64,${base64String}`);
const blob = await response.blob();
In the above code snippet, replace 'Your Base64 string here'
with your actual Base64 string. The resulting BLOB object will have the MIME type set to application/octet-stream
. You can modify the MIME type as per your requirements.
Conclusion
Converting a Base64 string into a BLOB object in JavaScript can be achieved using either the atob()
and Uint8Array()
approach or the fetch()
API. Choose the solution that best fits your needs and implement it in your code.
Remember to handle any errors that may occur during the conversion process and ensure that your Base64 string is valid.
Leave a Reply