以Blob格式下载PDF不能在Chrome iOS上运行

时间:2019-01-28 08:58:24

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

在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的代码,但是也失败了。

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

1 个答案:

答案 0 :(得分:0)

删除自定义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);
        })