当我增加
dataString
时,我收到此错误(在大约 8kb 文件大小之后)。
DOMException:无法在“Window”上执行“btoa”:要编码的字符串包含 Latin1 范围之外的字符。
let data = "data:text/csv;base64," + btoa(dataString);
let link = document.createElement("a");
link.href = data;
link.download = "name.csv";
link.click();
link.remove;
let data = "data:text/csv;base64," + base64EncodeUnicode(dataString);
let link = document.createElement("a");
link.href = data;
link.download = "name.csv";
link.click();
link.remove();
function base64EncodeUnicode(str) {
// First, escape the string as UTF-8 to ensure all characters are encoded properly
let utf8Bytes = new TextEncoder().encode(str);
// Then, convert the UTF-8 bytes to Base64
return btoa(String.fromCharCode.apply(null, utf8Bytes));
}
我们使用 TextEncoder API 将 dataString 编码为 UTF-8,然后将 UTF-8 字节转换为 Base64。此方法允许您处理更大或非拉丁字符集,而不会遇到 Latin1 范围限制。