Creating a Blob from a Base64 String in JavaScript
When working with binary data encoded as a base64 string, it may be necessary to convert it into a Blob object. This can be useful for displaying the data in a web browser or saving it to the user's device.
Decoding the Base64 String
The first step is to decode the base64 string into a string of byte characters. This can be achieved using the atob function.
const byteCharacters = atob(b64Data);
Converting Byte Characters to a Byte Array
Next, we need to convert the byte characters into a real typed byte array. This can be done by passing the byte characters to the Uint8Array constructor.
const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers);
Creating the Blob Object
Finally, we can wrap the byte array in an array and pass it to the Blob constructor to create the Blob object.
const blob = new Blob([byteArray], {type: contentType});
Performance Optimization
The above code works, but its performance can be improved by processing the byte characters in smaller slices. A slice size of 512 bytes is typically a good choice.
Example Function
Here is a function that converts a base64 string to a Blob object using the optimized approach:
const b64toBlob = (b64Data, contentType='', sliceSize=512) => { const byteCharacters = atob(b64Data); const byteArrays = []; for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) { const slice = byteCharacters.slice(offset, offset + sliceSize); const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } const blob = new Blob(byteArrays, {type: contentType}); return blob; };
Usage Example
To use the function, simply pass the base64 string and content type as arguments.
const blob = b64toBlob(b64Data, contentType);
The resulting Blob object can then be used to create an image or download the data.
The above is the detailed content of How to Convert a Base64 String to a Blob in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!