Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  25] [ 6]  / answers: 1 / hits: 17849  / 6 Years ago, wed, april 4, 2018, 12:00:00

I know that, in order to convert a BLOB object to a readable format (URL) in Javascript, I should use the createObjectURL() method, right ?



Example :



var blob = new Blob([Example], { type: text/plain });
url = window.URL.createObjectURL(blob);


My question is:



Is it possible to get the raw binary content of a BLOB ? so, I can get something like :



01000101 01111000 01100001 01101101 01110000 01101100 01100101 // Example in binary .

More From » binary

 Answers
9

Convert the blob to an ArrayBuffer (see 2 methods). Create an ArrayBufferView (Int8array in this case), spread it into an array, and then map the view to the binary representation of each number using Number.toString() with a radix of 2 - .toString(2).


Method 1 - Use the Blob.arrayBuffer() instance method to get a promise that resolves with the ArrayBuffer:




const blobToBinary = async (blob) => {
const buffer = await blob.arrayBuffer();

const view = new Int8Array(buffer);

return [...view].map((n) => n.toString(2)).join(' ');
};

const blob = new Blob([Example], { type: text/plain });

blobToBinary(blob).then(console.log);




Method 2 - Extract the data from the blob using a FileReader. To get an ArrayBuffer use FileReader.readAsArrayBuffer().




const blob = new Blob([Example], { type: text/plain });

const reader = new FileReader();

reader.addEventListener(loadend, function() {
const view = new Int8Array(reader.result);

const bin = [...view].map((n) => n.toString(2)).join(' ');

console.log(bin);
});

reader.readAsArrayBuffer(blob);




[#54764] Monday, April 2, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominickmackenziet

Total Points: 583
Total Questions: 101
Total Answers: 117

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
dominickmackenziet questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Fri, Feb 12, 21, 00:00, 3 Years ago
;