【问题标题】:Downloading PDF as Blob not working on Chrome iOS以 Blob 格式下载 PDF 无法在 Chrome iOS 上运行
【发布时间】:2023-03-16 11:15:02
【问题描述】:

在我的 Angular 7 应用程序中,我有以下代码用于在各种平台上下载 PDF。

this.http.get('/api/url', {responseType: 'blob'}).pipe(map(res => {
      return {
        filename: 'filename.pdf',
        data: res
      };
    }))
      .subscribe(
        res => {
          const fileBlob = new Blob([res.data], {type: 'application/pdf'});

          if (navigator && navigator.msSaveBlob) { // IE10+
            navigator.msSaveBlob(fileBlob, res.filename);
          } else if (navigator.userAgent.match('CriOS')) { // iOS Chrome
            const reader = new FileReader();
            reader.onloadend = () => {
              window.location.href = reader.result.toString();
            };
            reader.readAsDataURL(fileBlob);
          } else if (navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPhone/i)) { // iOS Safari and Opera
            const url: string = URL.createObjectURL(fileBlob);
            window.location.href = url;
          } else {
            const url: string = URL.createObjectURL(fileBlob);
            const a: any = document.createElement('a');
            document.body.appendChild(a);
            a.setAttribute('style', 'display: none');
            a.href = url;
            a.download = res.filename;
            a.click();
            URL.revokeObjectURL(url);
            a.remove();
          }
        }
      );

下载在除 Chrome iOS 之外的所有平台上都能正常运行。我主要关注this link 和其他一些类似的链接。

我也尝试过 Chrome iOS 的以下案例

const reader = new FileReader();
reader.onloadend = () => {
    window.open(reader.result.toString());
};
reader.readAsDataURL(fileBlob);

还将onloadend 替换为上面的onload 并尝试了两种方式。 另外,我还尝试了Safari 的代码,但也失败了。

知道我在这里可能遗漏了什么吗?

【问题讨论】:

    标签: ios angular google-chrome pdf-generation chrome-ios


    【解决方案1】:

    删除自定义 chrome ios 检查对我有用:

            ...subscribe(response => {
                const file = new Blob([response.body], {type: 'application/pdf'});
                const fileURL = (window.URL || window['webkitURL']).createObjectURL(file);
                const fileName = 'Whatever.pdf';
    
                const downloadLink = document.createElement('a');
                downloadLink.href = fileURL;
                downloadLink.download = fileName;
                document.body.appendChild(downloadLink);
                downloadLink.click();
                document.body.removeChild(downloadLink);
            })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-15
      • 2012-10-02
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多