patternjavascriptCritical
Creating a Blob from a base64 string in JavaScript
Viewed 0 times
creatingfromblobbase64stringjavascript
Problem
I have base64-encoded binary data in a string.
I would like to create a
I haven't been able to figure out how to create the
In some cases, I can avoid this by using a
However in most cases the
How can I decode a base64 string to a
const contentType = 'image/png';
const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
I would like to create a
blob: URL containing this data and display it to the user.const blob = new Blob(????, {type: contentType});
const blobUrl = URL.createObjectURL(blob);
window.location = blobUrl;
I haven't been able to figure out how to create the
Blob.In some cases, I can avoid this by using a
data: URL instead.const dataUrl = data:${contentType};base64,${b64Data};
window.location = dataUrl;
However in most cases the
data: URLs are prohibitively large.How can I decode a base64 string to a
Blob object in JavaScript?Solution
The
Each character's code point (charCode) will be the value of the byte. We can create an array of byte values by applying this using the
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset
Full Example:
`const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset
atob function will decode a base64-encoded string into a new string with a character for each byte of the binary data.const byteCharacters = atob(b64Data);
Each character's code point (charCode) will be the value of the byte. We can create an array of byte values by applying this using the
.charCodeAt method for each character in the string.const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i
You can convert this array of byte values into a real typed byte array by passing it to the Uint8Array constructor.
const byteArray = new Uint8Array(byteNumbers);
This in turn can be converted to a Blob by wrapping it in an array and passing it to the Blob constructor.
const blob = new Blob([byteArray], {type: contentType});
The code above works. However the performance can be improved a little by processing the byteCharacters in smaller slices, rather than all at once. In my rough testing 512 bytes seems to be a good slice size. This gives us the following function.
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset
const blob = b64toBlob(b64Data, contentType);
const blobUrl = URL.createObjectURL(blob);
window.location = blobUrl;
Full Example:
`const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset
Context
Stack Overflow Q#16245767, score: 1180
Revisions (0)
No revisions yet.