javascript 在 JS 中创建二进制 blob

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25949152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:17:26  来源:igfitidea点击:

Create binary blob in JS

javascriptfilebinaryhexblob

提问by user3491456

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?

生成的文件是一个纯文本文件,其中包含 ASCII 格式的十六进制数据。如何强制 Blob 按原样包含二进制数据而不是文本?

回答by Alan Mimms

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.

源自上面@Musa 的解决方案,所以我不能相信,但将其写为答案比我对他的答案的蹩脚评论更清楚。

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.

也许这更容易理解?个人觉得比较清楚。

回答by Musa

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

将您的数据转换为二进制数组,然后从中创建一个 blob。

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/

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