Home >Web Front-end >JS Tutorial >How to Create a JavaScript Blob from a Base64 String?

How to Create a JavaScript Blob from a Base64 String?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-21 14:11:09570browse

How to Create a JavaScript Blob from a Base64 String?

Creating a Blob from a Base64 String in JavaScript

Converting a base64-encoded string into a Blob object is a common task in JavaScript when dealing with binary data. This can be useful for displaying the data as an image or downloading it to the user's device.

Decoding the Base64 String

The first step is to decode the base64 string. This can be achieved using the atob function, which converts a base64-encoded string into a new string containing the original binary data.

const byteCharacters = atob(b64Data);

Converting to a Typed Byte Array

The atob function will produce a string of characters, each representing a byte. To convert these characters into actual bytes, we can use the .charCodeAt method to get the character code points. These code points will be the values of the bytes.

const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
}

Next, we can create a Uint8Array by passing the byteNumbers array to the constructor.

const byteArray = new Uint8Array(byteNumbers);

Creating the Blob

Finally, we can create the Blob object by wrapping the byteArray in an array and passing it to the Blob constructor.

const blob = new Blob([byteArray], {type: contentType});

Example

Here is an example of how to create a Blob from a base64 string:

const contentType = 'image/png';
const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';

const blob = new Blob([atob(b64Data)], {type: contentType});

Once you have created the Blob, you can use it to display the data to the user or download it to their device. You can use the URL.createObjectURL function to create a URL for the Blob, which you can then set as the src of an image or as the href of a download link.

The above is the detailed content of How to Create a JavaScript Blob from a Base64 String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn