从Base64字符串下载文件的JavaScript在IE中不起作用。

问题描述 投票:0回答:1

想用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.coma487964952247677。 在IE中也无法使用。

javascript internet-explorer base64
1个回答
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;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.