我有生成CSV文件,并通过一个HTTP / AJAX获取它返回到页面的服务。我想一个用户点击一个按钮,让服务被调用,然后有一个文件获取下载到用户的浏览器。
我想做到这一点的角路,虽然我承认这可能更多地与阿贾克斯或浏览器比Anguler本身。
该服务是在C#中,而这也正是它返回:
返回文件(Encoding.UTF8.GetBytes(WriteCSV(资源列表)),文/ CSV,results.csv);
控制器code调用该服务看起来像下面这样。它的工作原理,但我不知道该怎么办了成功:
$ scope.exportCSV =功能(){
$ HTTP({
方法:获取,
网址:ExportCSV
})。
错误(功能(数据,状态,头,配置){
警报(错误数据导出为CSV。);
});
};
解决方案
您不能启动从一个普通的ajax GET或POST下载,你必须做的传统方式,如: window.location的='URL'
,并设置了正确的内容类型正确的HTTP标头,这将促使在用户的浏览器下载对话框
I have a service that generates a CSV file and returns it to the page via an http/ajax get. I'd like a user to click a button, have the service get called, and then have the file get downloaded to the user's browser.
I would like to do this The Angular Way, although I recognize this may have more to do with Ajax or the browser than Anguler per se.
The service is in C#, and this is what it returns:
return File(Encoding.UTF8.GetBytes(WriteCSV(assetList)), "text/csv", "results.csv");
The controller code that calls the service looks like the following. It works, but I don't know what to do on success:
$scope.exportCSV = function () {
$http({
method: "get",
url: "ExportCSV"
}).
error(function (data, status, headers, config) {
alert("Error exporting data to CSV.");
});
};
解决方案
You can't initiate a download from a normal ajax GET or POST, you have to do the traditional way, eg window.location='url'
and set the correct http header with the correct content-type which will prompt the download dialog in the users browser