使用Angular通过Ajax下载文件

4
我有一个服务,它会生成一个CSV文件并通过http/ajax get返回到页面上。我希望用户点击按钮后调用该服务,然后将文件下载到用户的浏览器中。
我希望以Angular的方式实现这一点,尽管我认识到这可能更多地与Ajax或浏览器有关,而不是与Angular本身有关。
该服务使用C#编写,以下是其返回值:
return File(Encoding.UTF8.GetBytes(WriteCSV(assetList)), "text/csv", "results.csv");

调用服务的控制器代码如下。它能够工作,但是成功后该怎么办我并不清楚:

$scope.exportCSV = function () {
    $http({
        method: "get",
        url: "ExportCSV"
    }).
        error(function (data, status, headers, config) {
            alert("Error exporting data to CSV.");
        });
};

你能使用HTML5文件系统吗? - Ajay Beniwal
2个回答

5

您无法从普通的ajax GET或POST发起下载,必须使用传统方式,例如 window.location = 'url' 并设置正确的http头以及正确的内容类型,这将提示用户浏览器中的下载对话框。


2

可能更加“angular”的方法是让你的控制器设置一个标志来触发下载,但将核心功能放在一个指令中,该指令使用“download”属性构建一个元素,并在显示时,回调/观察器调用ng-click。

例如:

// put this in a template related to a given controller
<downloader ng-if="downloadready"></downloader>

// controller just needs to trigger the directive into action
module.controller(..., function($scope){
    $scope.downloadready = true; // trigger the directive to be created       
});

// and the directive code will build the element and click the button
module.directive('downloader', function ($compile) {
  return {
          restrict: 'E',
          replace: true,
          // values here can be placed in the template as variables and accessed in link()
          // but this is shortest to get the idea across
          template: '<a id="downloadbtn" class="btn" download="backup.json"></a>',
          link:function (scope, elm, attrs) {
              // this clicks the button outside the digest loop which the scope was updated in
              $timeout(function() {
                angular.element($('#downloadbtn')).triggerHandler('click');
              }, 0);
          }
     }
});

虽然我承认,这比更改 window.location 的重定向更让人费解。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接