javascript - JavaScript 从 Base64 字符串下载文件在 IE 中不起作用
问题描述
想要使用 javascript 将 Base64 保存/下载为 pdf 文件。下面的代码适用于 chrome,但不适用于 IE。我尝试了许多不同的方法,但没有在 Internet Explorer 中工作。
IE 有什么问题?
function Base64ToPdf(fileName, base64String) {
const linkSource = "data:application/pdf;base64," + base64String;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
// Test
var string = 'Hello World!';
var encodedString = btoa(string);
Base64ToPdf("test.pdf", encodedString);
我尝试过使用https://stackoverflow.com/a/48796495/2247677 ,它在 IE 中也不起作用。
解决方案
我尝试了许多将 Base64 下载为 PDF 的解决方案,但 IE 没有成功。最后,我决定首先将 Base64 转换为 Blob,并且它在 IE 11 和 chrome 中也可以正常工作。
完整的代码看起来像 TS :
export class FileHelper {
static Base64ToPdf(fileName: string, base64String: string) {
if (window.navigator && window.navigator.msSaveBlob) {
const blob = this.Base64toBlob(base64String);
window.navigator.msSaveBlob(blob, fileName);
} else {
const linkSource = "data:application/pdf;base64," + base64String;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
}
static Base64toBlob(
b64Data: string,
contentType = "application/pdf",
sliceSize = 512
) {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: contentType });
return blob;
}
}
推荐阅读
- bash - 在一个命令中连接到标准输出并从标准输出读取
- javascript - 如何使用 Javascript 拥有多个按钮?
- docker - docker-compose 文件无法构建图像
- arrays - winbugs:数组索引大于数据类型分类(序数)模型的数组上限
- java - 如何正确读取 zip 文件到字符串?
- c# - Azure Pipelines dotnet restore 错误:$(AssemblyInfo.AssemblyFileVersion)' 不是有效的版本字符串
- java - 使用 Stream 从文件中逐字存储
- python - 如何在每8个字符的字符串中插入一个子字符串并在Python中继续?
- forms - 如何让 Flutter 用户在 FormBuilderTextField(Flutter Form Builder 包)中输入标签?
- angular - 将管道停在中间