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?
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.
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.
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.
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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With