Chrome 多个文件下载警告,尽管只有一个文件

Chrome Warning of Multiple Files Download, despite only being one file

我以前从未遇到过这个问题,但每当我尝试以编程方式下载文件时,chrome 都会阻止尝试并警告我,该页面想要下载多个文件......但它们不是。

我收到了一个 JSON,其中包含一些信息,但其中一个字段称为 documentContentB64,并且只有一个 base64 编码的 pdf 文件。如果我允许 Chrome 下载多个文件,下面的代码(为简洁起见保持简单一点)最后会按预期给我一个 PDF。

  downloadInvoicePdfData() {
    this.httpClient.get('<url>',
      { observe: 'response' }).subscribe((invoiceFile: any) => {
        this.downloadPdf(invoiceFile.body.documentContentB64);
      });
  }

  private downloadPdf(base64File: string) {
    const downloadLink = document.createElement('a');
    const file = base64File;
    downloadLink.href = 'data:application/pdf;base64,' + file;
    downloadLink.download = `invoice.pdf`;
    downloadLink.dispatchEvent(new MouseEvent('click', { bubbles: true, view: window }));

    window.URL.revokeObjectURL(downloadLink.href);
    downloadLink.remove();
  }

好吧,我对此没有合理的解释。我回到了我的“旧”解决方案,它适用于 BLOB 并且......它很简单。 Chrome 在提供 blob 的 ObjectUrl 时执行几乎相同的步骤来设置程序化下载时不会抱怨。我需要研究一下。

async downloadPdf(base64File: string) {
    this.fileLink = 'data:application/pdf;base64,' + base64File;

    const base64Response = await fetch(this.fileLink);
    const blob = await base64Response.blob();

    const downloadLink = document.createElement('a');
    downloadLink.href = window.URL.createObjectURL(blob);
    downloadLink.download = 'invoice.pdf';
    downloadLink.dispatchEvent(new MouseEvent('click', { bubbles: true, view: window }));
    window.URL.revokeObjectURL(downloadLink.href);
    downloadLink.remove();
  }