简体   繁体   English

非拉丁字符的 Base64 编码失败

[英]Base64 encoding fails for non-latin characters

I'm working on a VueJS project where I generate SVG images based on input.我正在开发一个 VueJS 项目,在该项目中我根据输入生成 SVG 图像。 After they have been generated, I send data from them to a back end API as a base64 encoded string.生成它们之后,我将它们中的数据作为 base64 编码字符串发送到后端 API。

Now, whenever I try to encode the string with UTF8 characters, I get the following error:现在,每当我尝试使用 UTF8 字符对字符串进行编码时,都会收到以下错误:

Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

I tried to solve the issue with replacing all characters in the HTML with their Unicode code points.我试图用它们的 Unicode 代码点替换 HTML 中的所有字符来解决这个问题。 However, whenever I try to get the DOM element, the Unicode encoded characters are reverted back to their plain text format.但是,每当我尝试获取 DOM 元素时,Unicode 编码字符都会恢复为纯文本格式。

How can I obtain the HTML as a base64 encoded string?如何获取 HTML 作为 base64 编码字符串?

The issue can be seen in a fiddle here .这个问题可以在这里看到。

I've tried both using XMLSerializer and just running innerHTML.toString() :我已经尝试过使用XMLSerializer和运行innerHTML.toString()

let svgEl = this.$el.querySelector('.svg-container svg')
if (!svgEl) {
  console.log('no poster element')
  return
}

// Using XMLSerializer:
console.log(btoa(new XMLSerializer().serializeToString(posterEl))

// Using innerHTML:
console.log(btoa(posterEl.innerHTML.toString()))

Both the above examples yield the same error.上述两个示例都产生相同的错误。

Thanks.谢谢。

You can follow the answer steps in for this answered question: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.您可以按照此已回答问题的回答步骤操作: 无法在“Window”上执行“btoa”:要编码的字符串包含 Latin1 范围之外的字符。

The key of solution is to encode the string by this way:解决方案的关键是通过这种方式对字符串进行编码:

btoa(unescape(encodeURIComponent(str)));

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

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