【问题标题】:Angular - downloading a file doesn't work in EdgeAngular - 在 Edge 中无法下载文件
【发布时间】:2019-07-05 10:08:33
【问题描述】:

我有一个 Angular 7 应用程序,它调用一个 ASP.NET Web API 函数,该函数以.xlsx Excel 文件的形式将数据返回给 Angular。

使用此代码,然后我创建一个不可见的<a> 标签并单击它以开始将该二进制文件下载到客户端:

this.reportService.createReport(this.reportOption,
    (data) => {
        const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });

        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        document.body.appendChild(a);

        a.setAttribute('style', 'display: none');
        a.href = url;
        a.download = fileName;
        a.click();

        window.URL.revokeObjectURL(url);
        a.remove();
    },
    (error: string) => {
        this.messsageService.showError(error);
    });

此代码在 Firefox 和 Chrome 中完美运行 - 完全没有问题。

但在 MS Edge 中,由于某种原因,没有开始下载。我在 Javascript 控制台中没有看到任何错误,它只是说“下载成功开始”-但没有提示用户将文件保存在哪里-并且文件也没有静默下载到配置的默认下载目录中.

有什么想法吗?有没有其他人在 Edge 中看到过这一点,并找到了解决方案?

【问题讨论】:

  • 如果 get 请求实际发生并且等于 chrome 请求,那么您能否从网络控制台提供更多详细信息,因此出现来自 ASP.NET 的相同响应?
  • @Lucho:控制台输出似乎与 Chrome 中的相同——没有错误、没有警告、没有任何问题的提示——文件只是没有返回给客户端......跨度>

标签: angular asp.net-web-api download microsoft-edge


【解决方案1】:

在 IE/Microsoft Edge 浏览器中,您可以使用 msSaveOrOpenBlob 方法下载文件。请尝试修改您的代码如下:

//change to your format.
var blob = new Blob([byteArray], { type: 'application/pdf' });
//output file name
var fileName = "test.pdf";

//detect whether the browser is IE/Edge or another browser
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
  //To IE or Edge browser, using msSaveorOpenBlob method to download file.
  window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
    //To another browser, create a tag to downlad file.
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    document.body.appendChild(a);
    a.setAttribute('style', 'display: none');
    a.href = url;
    a.download = fileName;
    a.click();

    window.URL.revokeObjectURL(url);
    a.remove();
}

【讨论】:

  • 谢谢 - 看起来很有希望。在我的本地机器上运行良好 - 我必须在测试服务器上对其进行测试才能验证。
猜你喜欢
  • 2020-02-07
  • 2018-10-06
  • 2021-04-19
  • 1970-01-01
  • 2019-08-26
  • 1970-01-01
  • 1970-01-01
  • 2017-07-01
  • 2018-09-05
相关资源
最近更新 更多