以编程方式从IE中的回调开始下载

时间:2016-03-24 11:20:20

标签: javascript angularjs node.js internet-explorer

尝试在角度+节点设置中在IE中开始下载时遇到问题。

首先,这是我目前的流程:

  • 用户点击下载按钮
  • 它从节点服务器请求文件
  • 节点服务器生成文件,将其发送回JS控制器
  • JS控制器为该文件生成一个URL,并将其作为下载打开

我到目前为止使用的版本看起来像这样(为了清楚起见,简化了):

var self = this;
var invisibleLink = document.getElementById('invisible-link');

this.services.http.post("createPdf", {foo: 'bar}, {responseType: 'arraybuffer'})
  .then(function(response){
    var file = new Blob([response.data], {type: 'application/pdf'});
    var fileURL = window.URL.createObjectURL(file);
    invisibleLink.href = fileURL;
    invisibleLink.download = 'myDownloadedFile';
    invisibleLink.click();
  });

这很好用,它很流畅,一切......在FF和Chrome中。在IE(11)中,我收到“错误:访问被拒绝”。

显然不接受.download和/或.click(),所以在其他SE问题之后,我尝试使用window.location。不幸的是,这似乎也不起作用。

这是我尝试过的,结果如下:

window.location.href = fileURL;
// Error: Permission denied

window.location.href = file;
// Opens "http://myurl.com/[object%20Blob]"

window.location = fileURL;
// Error: Access is denied.

window.location = file;
// Opens "http://myurl.com/[object%20Blob]"

window.open= file;
// Nothing happens

window.open= fileURL;
// Nothing happens

// For all tests, using document instead of window had the exact same results

我真的真的需要从回调中触发下载,考虑:

  • 1 /生成文件,因此没有现有的URL
  • 2 /文件生成可能需要1到20秒之间的任何时间,所以使用timeOut的任何内容都会有问题

无论如何从IE中的回调开始下载?

2 个答案:

答案 0 :(得分:0)

一种解决方法是将数据缓存在服务器的内存中很短的时间(可能只需几分钟),并将其与UUID相关联。然后从服务器返回UUID,让客户端向服务器上的URL发送另一个请求(这次是通过导航到新URL,而不是使用AJAX),该URL将UUID作为参数发回数据。

答案 1 :(得分:0)

对于任何发现这一点的人:最简单的解决方案最终是使用模块

使用FileSaver.js

var self = this;

this.services.http.post("createPdf", {foo: 'bar}, {responseType: 'arraybuffer'})
  .then(function(response){
    var file = new Blob([response.data], {type: 'application/pdf'});
    saveAs(file, 'myDownloadedFile');
  });