Creating binary blob in JS

I create the client part of the file, I have the data in hexadecimal and just want the user to download the generated file.

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

The resulting file is a text file with hexadecimal data in ASCII. How can I make Blob contain binary data as is, and not as text?

+5
source share
2 answers

Convert the data to a binary array, and then create a blob from it.

 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/

+2
source

Obtained from @Musa's solution above, so I can’t get a loan, but it’s clearer to write this as an answer than my lame comment on 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 find this more clear.

+2
source

Source: https://habr.com/ru/post/1203036/


All Articles