1

在我的 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 之外的所有平台上都能正常运行。我主要关注这个链接和其他一些类似的链接。

我还为 Chrome iOS 尝试了以下案例

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

也替换onloadendonload上面并尝试了两种方式。另外,我也尝试了代码Safari,但也失败了。

知道我在这里可能缺少什么吗?

4

1 回答 1

-2

删除自定义 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);
        })
于 2019-03-24T07:05:26.787 回答