如何在angularjs中请求下载文件

How to request files for download aync in angularjs?

本文关键字:请求 下载 文件 angularjs      更新时间:2023-09-26

我正在使用angularjs,想提供一个下载按钮。

问题:在从后端返回文件之前,该按钮会在后端触发长时间运行(15 秒)的进程。同时不应阻止用户。

所以我想我可以在点击时使用 angularjs 在后台获取文件,并在异步接收时提供下载。

<a ng-href="{{service.pdf()}}" target="_blank">download</a>
function pdf() {
    return "http://path.to.the.service/filename.pdf";   
}

这样我就可以直接打开另一个页面。这有效,但我想在后台获取它,而不是打开新窗口。

这可能吗?

也许最好的解决方案是为您使用此 html 代码按钮?让我们试试这个:

<a ng-href="{{service.pdf()}}" target="_self">download</a>

但你也可以用AngularJS做到这一点。例如,您有如下所示的代码:

<button type="button" ng-click="downloadFile()" name="button">Download file</button>

ng-单击调用你下载文件()函数。您可以在此功能中执行下载操作:

$http.get('/path/to/your/file', { responseType: 'blob' })
.then((response) => {
    var windowUrl = $window.URL || $window.webkitURL;
    var anchor = angular.element('<a></a>');
    anchor
    .attr({
      href: windowUrl.createObjectURL(response.data),
      download: 'file.txt',
    });
    anchor[0].click();
  }
});

此解决方案也适用于具有基于令牌的授权(使用拦截器)的 API。但是如果你想在IE和Mozilla中保存blob文件,你应该添加更多的代码。

另一种方法是使用隐藏的 iframe 下载文件。这可用于在一个页面中下载多个文件的场景 - <a>方法在 FF 上不起作用。

  $scope.downloadUrl = function (url) {
        var oIframe = window.document.createElement('iframe');
        var $body = $(document.body);
        var $oIframe = $(oIframe).attr({
            src: url,
            style: 'display:none;'
        });
        $body.append($oIframe);
   }

您可以在Chrome和FF中下载多个文件,但是IE您不走运。