Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create binary blob in JS

I'm generating a file client-side, I have the data in hexadecimal and just want to let the user download the generated file.

var blob = new Blob([hexData], {type: "application/octet-stream"});
console.log(URL.createObjectURL(blob));

The resulting file is a plain-text file containing hex data in ASCII. How can I force the Blob to contain the binary data as is and not as text?

like image 566
user3491456 Avatar asked Sep 20 '14 13:09

user3491456


People also ask

What is Blob () in JS?

The Blob object represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. Blobs can represent data that isn't necessarily in a JavaScript-native format.

Is blob and binary same?

A binary large object (BLOB or blob) is a collection of binary data stored as a single entity. Blobs are typically images, audio or other multimedia objects, though sometimes binary executable code is stored as a blob.

What is binary data in JavaScript?

Binary data in JavaScript is implemented in a non-standard way, compared to other languages. But when we sort things out, everything becomes fairly simple. The basic binary object is ArrayBuffer – a reference to a fixed-length contiguous memory area.


2 Answers

Convert you data to a binary array then create a blob from that.

var byteArray = new Uint8Array(hexdata.length/2);
for (var x = 0; x < byteArray.length; x++){
    byteArray[x] = parseInt(hexdata.substr(x*2,2), 16);
}
var blob = new Blob([byteArray], {type: "application/octet-stream"});

http://jsfiddle.net/mowglisanu/15h9o3d5/

like image 181
Musa Avatar answered Sep 21 '22 14:09

Musa


Derived from @Musa's solution above so I cannot take credit, but it's clearer to write this as an answer than my lame comment to his answer.

var byteArray = new Uint8Array(hexdata.match(/.{2}/g)
                              .map(e => parseInt(e, 16)));
var blob = new Blob([byteArray], {type: "application/octet-stream"});

Maybe this is easier to understand? I personally think it is clearer.

like image 26
Alan Mimms Avatar answered Sep 20 '22 14:09

Alan Mimms