【问题标题】:JavaScript Download file from Base64 string not working in IEJavaScript 从 Base64 字符串下载文件在 IE 中不起作用
【发布时间】:2020-05-08 09:35:09
【问题描述】:

想要使用 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 中也不起作用。

【问题讨论】:

  • “IE 出了什么问题?”从哪里开始...
  • @RobbyCornelissen 可能是如何修复此代码??
  • @RobbyCornelissen 我已经测试了stackoverflow.com/a/48796495/2247677 给出的解决方案,但没有一个适用于 IE。
  • 我将删除我的近距离投票,但怀疑你会得到更好的解决方案。
  • IE does not support the download attribute on <a> 元素。我想这就是上面的代码不能按预期工作的原因。

标签: javascript internet-explorer base64


【解决方案1】:

我尝试了许多将 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;
  }
}

【讨论】:

  • 感谢您发布此问题的解决方案。我建议你尝试在 48 小时后标记你自己对这个问题的答案,当它可以标记时。它可以在未来帮助其他社区成员解决类似的问题。感谢您的理解。
猜你喜欢
  • 2016-04-14
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-05
  • 1970-01-01
相关资源
最近更新 更多