简体   繁体   English

Javascript下载没有base64的二进制数据

[英]Javascript download binary data without base64

I want to download some binary data but Chrome forces it to utf-8 which messes up the bytes. 我想下载一些二进制数据,但Chrome强制将其转换为utf-8,从而弄乱了字节。 If I set href to a data URI and use base64 encoding it works, but I want to avoid that and use a BLOB instead. 如果我将href设置为数据URI并使用base64编码,则可以使用,但是我想避免这种情况,而应使用BLOB。

Is there a way to stop Chrome from converting this binary data to utf-8? 有没有办法阻止Chrome将二进制数据转换为utf-8?

 const data = "\\x00\\xff\\xfe\\xe2" console.log(data) const file = new Blob([data]) const a = document.getElementById("a") const url = URL.createObjectURL(file) a.href = url; a.download = "test.txt"; 
 <a id="a">Download</a> 

In this example, you can see that my string contains the bytes 在此示例中,您可以看到我的字符串包含字节

00 ff fe e2

and I convert that string to a blob. 然后将该字符串转换为Blob。 But when you download the file in Chrome and look at the bytes again you'll find 但是,当您在Chrome中下载文件并再次查看字节时,您会发现

20 c3 bf c3 be c3 a2

instead. 代替。 What I think is happening is that chrome takes each byte, reads it as utf-16 and converts it to utf-8. 我认为发生的事情是chrome占用了每个字节,将其读取为utf-16并将其转换为utf-8。 For example fe is þ when read as utf-16 but c3 be in utf-8 例如,当读为utf-16时feþ ,而c3 be utf-8

Strings are implicitly encoded as UTF-8 by the Blob constructor, so pass a typed array instead, such as Uint8Array : Blob构造函数将字符串隐式编码为UTF-8,因此应传递一个类型化的数组,例如Uint8Array

 const data = "\\x00\\xff\\xfe\\xe2" console.log(data) const file = new Blob([Uint8Array.from(data, c => c.charCodeAt(0))]) const a = document.getElementById("a") const url = URL.createObjectURL(file) a.href = url; a.download = "test.txt"; 
 <a id="a">Download</a> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM