CryptoBird
CryptoBird

Reputation: 546

Getting the binary content of a BLOB

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 .

Upvotes: 10

Views: 24122

Answers (2)

Ori Drori
Ori Drori

Reputation: 191916

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);

Upvotes: 13

Máté Safranka
Máté Safranka

Reputation: 4116

You can use a FileReader to get the contents of the BLOB as a byte array:

var reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onloadend = (event) => {
    // The contents of the BLOB are in reader.result:
    console.log(reader.result);
}

https://developer.mozilla.org/en-US/docs/Web/API/FileReader

https://developer.mozilla.org/en-US/docs/Web/API/Blob#Example_for_extracting_data_from_a_Blob

Upvotes: 5

Related Questions