published under license Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)copy! share!
posted in category Software Development & Programming / JavaScript
posted at 12. Oct '19
last updated at 11. May '21
Howto Read Blob in JavaScript
Assuming the content is a binary string, i.e. no interpretation of characters, no encoding. Just an array of bytes, an image for example.
Find out how streaming API is converted into a promise in How to Covnert Stream Into Promise.
With FileReader
Usually FileReader is used to read Blobs or Files.
According to a blogpost about reading ArrayBuffers reading with FileReader is 27 times slower than converting it with ArrayBuffers.
function convertBlobToBinaryString(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
resolve(reader.result);
}
reader.onabort = () => {
reject(new Error('Reading blob aborted'));
}
reader.onerror = () => {
reject(new Error('Error reading blob'));
}
reader.readAsBinaryString(blob);
});
}
With Arraybuffer
function blobToBinaryStringArrayBuf(blob) {
return blob.arrayBuffer()
.then(ab => new Uint8Array(ab))
.then(charArr => {
const mapped = [];
for(let i = 0; i < charArr.length; i = i + 1) {
mapped.push(String.fromCharCode(charArr[i]))
}
return mapped.join('');
});
}
Example
Save it into a file, open it in a browser and look into developer console.
You should see:
blob1: ��~sirius black blob.html:29:33
blob2: ��~hermione granger blob.html:48:33
HTML file:
<!DOCTYPE html>
<html>
<header><meta charset="utf-8" /></header>
<body>
<script>
function convertBlobToBinaryString(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
resolve(reader.result);
}
reader.onabort = () => {
reject(new Error('Reading blob aborted'));
}
reader.onerror = () => {
reject(new Error('Error reading blob'));
}
reader.readAsBinaryString(blob);
});
}
const blob1 = new Blob(['\x00\x07\x7Esirius black']);
convertBlobToBinaryString(blob1)
.then(result => console.log('blob1: ' + result));
</script>
<script>
// cannot use .map on Uint8Array, because it doesn't work properly
function blobToBinaryStringArrayBuf(blob) {
return blob.arrayBuffer()
.then(ab => new Uint8Array(ab))
.then(charArr => {
const mapped = [];
for(let i = 0; i < charArr.length; i = i + 1) {
mapped.push(String.fromCharCode(charArr[i]))
}
return mapped.join('');
});
}
const blob2 = new Blob(['\x00\x07\x7Ehermione granger']);
blobToBinaryStringArrayBuf(blob2)
.then(result => console.log('blob2: ' + result))
</script>
</body>
</html>
That’s all.
Add Comment