在 Angular 中从服务器下载文本/csv 内容作为文件

2023-12-24

我正在尝试流式传输csv来自 Node.js 服务器的文件。服务器部分非常简单:

server.get('/orders' function(req, res) {
  res.setHeader('content-type', 'text/csv');
  res.setHeader('content-disposition', 'attachment; filename='orders.csv');
  return orders.pipe(res); // assuming orders is a csv file readable stream (doesn't have to be a stream, can be a normal response)
}

在我的角度控制器中我试图做这样的事情

$scope.csv = function() {
    $http({method: 'GET', url: '/orders'});
};

当点击按钮时会调用此函数ng-click在我看来 :

<button ng-click="csv()">.csv</button>

我查看了有关从 Angular 服务器下载文件的其他答案,但没有找到任何对我有用的内容。有没有通用的方法来做到这一点?看起来应该很简单。


$http服务返回一个promise它有两个回调方法,如下所示。

$http({method: 'GET', url: '/someUrl'}).
  success(function(data, status, headers, config) {
     var anchor = angular.element('<a/>');
     anchor.attr({
         href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
         target: '_blank',
         download: 'filename.csv'
     })[0].click();

  }).
  error(function(data, status, headers, config) {
    // handle error
  });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Angular 中从服务器下载文本/csv 内容作为文件 的相关文章

随机推荐