首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用jQuery Ajax调用从ASP.NET Web Api下载CSV文件

如何使用jQuery Ajax调用从ASP.NET Web Api下载CSV文件
EN

Stack Overflow用户
提问于 2013-03-11 16:40:01
回答 3查看 22.6K关注 0票数 18

我正在研究如何从jQuery ajax调用从ASP.NET Web Api下载CSV文件。CSV文件是基于自定义CsvFormatter从Web API服务器动态生成的。

来自jQuery的Ajax:

   $.ajax({
        type: "GET",
        headers: {
            Accept: "text/csv; charset=utf-8",
        },
        url: "/api/employees",
        success: function (data) {
        }
    });

在服务器上,从BufferedMediaTypeFormatter派生的EmployeeCsvFormatter实现方式类似于下面的文章

http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

public class EmployeeCsvFormatter : BufferedMediaTypeFormatter
{
    public EmployeeCsvFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/csv"));
    }
    ...
}

我还添加了覆盖方法,以表明我想以正常的方式下载文件(可以在下载选项卡中看到下载文件):

 public override void SetDefaultContentHeaders(Type type, 
    HttpContentHeaders headers, MediaTypeHeaderValue mediaType)       
{
    base.SetDefaultContentHeaders(type, headers, mediaType);
    headers.Add("Content-Disposition", "attachment; filename=yourname.csv");
    headers.ContentType =  new MediaTypeHeaderValue("application/octet-stream");
}

但它不工作,下载文件没有显示在状态栏或在Chrome的下载选项卡中,即使从Fiddler,我看到它的响应似乎是正确的:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/11.0.0.0
Date: Mon, 11 Mar 2013 08:19:35 GMT
X-AspNet-Version: 4.0.30319
Content-Disposition: attachment; filename=yourname.csv
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: application/octet-stream
Content-Length: 26
Connection: Close

1,Cuong,123
1,Trung,123

我在ApiController中的方法:

public EmployeeDto[] Get()
{
    var result = new[]
               {
                   new EmployeeDto() {Id = 1, Name = "Cuong", Address = "123"},
                   new EmployeeDto() {Id = 1, Name = "Trung", Address = "123"},
               };

    return result;
}

它一定是错在什么地方,我还没弄清楚。如何才能像正常方式一样下载CSV文件?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15334227

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档