chrome PDF viewer无法下载文件

Dav*_*LIu 8 pdf google-chrome pdf-viewer

这是我的情况,我有一台运行PDF生成器的服务器,当我用一些参数发出请求时,它会给我一个PDF文件,PDF不会存储在运行时生成的服务器中.

一切顺利,我可以在chrome的PDF查看器中打开PDF,但如果要下载文件,则会出现错误,如图所示. 在此输入图像描述

因为Chrome转到原始URL来请求文件,但该文件不是服务器上的静态资源.

我不知道是否有人遇到过这个问题?

flo*_*lob 8

每当您离开网站时,您都会创建用于创建对象 URL( window.URL.createObjectURL(...))的对象,该对象将被垃圾收集。所以你需要以某种方式保留对该对象的引用。

这适用于我们在 Chrome、Firefox、Safari、iOS Safari 和 Android 中首先在支持浏览器的新标签中显示 PDF,然后允许下载(在 IE 中它只是开始下载):

function openPdfInNewTab(url,
                         postData,
                         description = 'Document',
                         filename = description + '.pdf') {
  if (!window.navigator.msSaveOrOpenBlob) {
    var tabWindow = window.open('', '_blank');
    var a = tabWindow.document.createElement('a');
    a.textContent = 'Loading ' + description + '..';
    tabWindow.document.body.appendChild(a);
    tabWindow.document.body.style.cursor = 'wait';
  } else {
    spinnerService.show('html5spinner');
  }

  $http.post(url, postData, {responseType: 'arraybuffer'})
    .then(function showDocument(response) {
      var file = new Blob([response.data], {type: 'application/pdf'});
      if (window.navigator.msSaveOrOpenBlob) {
        spinnerService.hide('html5spinner');
        window.navigator.msSaveOrOpenBlob(file, filename);
      } else {
        tabWindow.document.body.style.cursor = 'auto';
        var url = a.href = window.URL.createObjectURL(file);
        a.click();
        a.download = filename;
      }
      $timeout(function revokeUrl() {
        window.URL.revokeObjectURL(url);
      }, 3600000);
    }, handleDownloadError);
}
Run Code Online (Sandbox Code Playgroud)

我们一直在新的浏览器选项卡中打开 PDF 并遇到了类似的问题。

对我们来说,当我们使用 window.URL.createObjectURL 而不是 tabWindow.URL.createObject 时它又开始工作了,它显示了 PDF 但不允许下载。