简体   繁体   English

将HTML转换为base64不能正确编码某些字符

[英]Converting HTML to base64 is not encoding certain characters correctly

I am trying to convert an HTML string to base64 which I will then display in an iframe but I am running into some issues. 我正在尝试将HTML字符串转换为base64,然后将其显示在iframe中,但遇到一些问题。 When I encode the string as base64 and view it as a data URI, it is display non-breaking spaces as 'Â', and other characters such as apostrophes and dashes are displayed as random ASCII characters. 当我将字符串编码为base64并将其视为数据URI时,它会以“”显示不间断空格,而其他字符(例如撇号和破折号)则会显示为随机ASCII字符。

This is how I am converting the string to base64: 这就是我将字符串转换为base64的方式:

var blob = new Blob([message], {
    type: contentType
});
var reader = new FileReader();
reader.onload = function (e) {
     let result = e.target.result;
};
reader.readAsDataURL(blob);

Any ideas on how to prevent this? 关于如何防止这种情况的任何想法? Thanks! 谢谢!

There is no reason to do what you're doing. 没有理由去做你正在做的事情。 Data URIs are almost always the wrong choice. 数据URI几乎总是错误的选择。 Base-64 encoding adds 33% overhead of size and wastes CPU. Base-64编码增加了33%的大小开销,并浪费了CPU。 Data URIs are subjected to some strict size limits . 数据URI 受到一些严格的大小限制

Use a Blob/Object URL instead. 请改用Blob /对象URL。

iframe.src = URL.createBlobURL(blob);

https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

As to your UTF-8 encoding problem, the issue is likely in your file itself, in that if you're not serving from a server which sets the character set in the headers, it needs to be in the file: 至于您的UTF-8编码问题,问题可能出在文件本身,因为如果您不是从服务器设置标题中的字符集,则该文件必须位于文件中:

<meta charset="UTF-8">

There's no server here, so you need to declare it in the file. 这里没有服务器,因此您需要在文件中声明它。

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

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