采用了棱角分明下载通过Ajax文件 [英] Using Angular to Download a File via Ajax

查看:112
本文介绍了采用了棱角分明下载通过Ajax文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有生成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

这篇关于采用了棱角分明下载通过Ajax文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆