在 Angular 中从服务器下载文本/csv 内容作为文件 [英] Download text/csv content as files from server in Angular
问题描述
我正在尝试从 node.js 服务器流式传输 csv
文件.服务器部分非常简单:
I am trying to stream a csv
file from a node.js server. The server portion is very simple :
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)
}
在我的角度控制器中,我正在尝试做这样的事情
In my angular controller I am trying to do something like this
$scope.csv = function() {
$http({method: 'GET', url: '/orders'});
};
在我的视图中单击带有 ng-click
的按钮时会调用此函数:
This function is called when there's a click on a button with ng-click
in my view :
<button ng-click="csv()">.csv</button>
我查看了有关从 Angular 中的服务器下载文件的其他答案,但没有找到任何对我有用的答案.有没有一种通用的方法来做到这一点?看起来应该很简单.
I have looked at other answers about downloading files from server in Angular, but didn't find anything that worked for me. Is there a common way to do this ? Seems like something that should be simple.
推荐答案
$http
服务返回一个 promise
,它有两个回调方法,如下所示.
$http
service returns a promise
which has two callback methods as shown below.
$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
});
这篇关于在 Angular 中从服务器下载文本/csv 内容作为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!