前端将二进制数据流转为文件,Javascript:如何将十六进制数据转换为二进制文件并将其写入文件...

I have a bunch of hex values and I have to convert it into binary data before write them into a file.

I trasformed the hex string in an array of integers, then I convert each integer to a char:

// bytes contains the integers

str = String.fromCharCode.apply(String, bytes);

now I create the blob file and download it:

var blob = new Blob([str], {type: "application/octet-stream"});

saveAs(blob, "file.bin");

but something goes wrong: if I print the length of bytes and the length of str I have the same value (512), but the file contains 684 chars, and of course it isn't how I expect it.

So I have:

512 pairs of hex values ->

512 integers ->

512 chars ->

I save the file ->

684 chars inside the file.

What am I doing wrong? I even tried to add the charset to the blob file, ie:

var blob = new Blob([str], {type: "application/octet-stream;charset=UTF-8,"});

but with no success.

EDIT:

Original HEX:

o8vJb.png

Saved file:

47f34814bff1f105b1524fcae0e9b279.png

解决方案

Thanks to Andrey I found the solution:

I have to write in binary mode, so:

var ab = new ArrayBuffer(bytes.length); //bytes is the array with the integer

var ia = new Uint8Array(ab);

for (var i = 0; i < bytes.length; i++) {

ia[i] = bytes[i];

}

var blob = new Blob([ia], {type: "application/octet-stream"});

saveAs(blob, id + "_<?php echo $report['md5']; ?>.bin");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值