JS - 通过XHR在新标签中打开PDF - 带文件名和auth标头

时间:2017-05-04 09:12:31

标签: javascript rest pdf xmlhttprequest

感谢您阅读!

我想从REST后端打开一个PDF,它通过XHR加载到一个带有指定文件名和授权标题的新选项卡中。

到目前为止,我设法用这个(包括auth标头和文件名)下载它:

// saves XHR stream as file with configurable filename
downloadXHRFile:function(endpoint,data,method,filename,errorcallback,mimetype){

   bsLoadingOverlayService.start();

   var def = $q.defer();

   var token = localStorageService.get('token');
   var xhr = new XMLHttpRequest();

   xhr.open(method, CONFIG.URL+endpoint, true);
   xhr.setRequestHeader('Authorization', 'Bearer '+token);
   xhr.setRequestHeader('Content-Type', 'application/json');

   xhr.responseType = 'arraybuffer';

   xhr.onload = function(e) {
      if (this.status == 200) {
         var blob=new Blob([this.response], {type:mimetype});
         var link=document.createElement('a');
         link.href=window.URL.createObjectURL(blob);
         link.download=filename;
         link.click();
         bsLoadingOverlayService.stop();
      }else{
         bsLoadingOverlayService.stop();
         errorcallback(xhr.statusText);
      }
      def.resolve();
   };
   xhr.send(
      JSON.stringify(data)
   );

   return def;
},

此外,我设法使用以下代码(包括auth标头)在新选项卡中打开它。 不幸的是,URL(以及文件名)看起来像这样:

团块:http://localhost:3000/0857f080-d152-48c6-b5fb-6e56292db651

可能它可以像上面那样解决,但我找不到解决方案。 有人聪明地知道如何在新标签中设置文件名吗?

// opens XHR filestream in tab
openXHRFile: function(endpoint,filename,errorcallback){

   var token = localStorageService.get('token');
   var our_url = CONFIG.URL+endpoint;

   var win = window.open('_blank');

   downloadFile(our_url, function(blob) {
      var url = URL.createObjectURL(blob);
      win.location = url;
   });

   function downloadFile(url, success) {
      var xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);

      xhr.setRequestHeader("Authorization", 'Bearer '+token);
      // xhr.setRequestHeader('Content-Type', 'application/json');

      xhr.responseType = "blob";
      xhr.onreadystatechange = function() {
         if (xhr.readyState == 4) {
            if (success) success(xhr.response);
         }else{

         }
      };
      xhr.send(null);
   }
},

0 个答案:

没有答案