我正在研究如何通过 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) {
}
});
在服务器上,EmployeeCsvFormatter
的实现类似于下面的文章,派生自 BufferedMediaTypeFormatter
:
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 文件使其工作?
最佳答案
jQuery Plugin for Requesting Ajax-like File Downloads不用 Ajax 就可以吗 using a simple form submit .
内部:
jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
.appendTo('body').submit().remove()
它有一个 ajax 风格的接口(interface),所以从外部你可以这样调用它
$.download('/api/employees','format=csv');
另一种简单的方法使用:
$('#btnDownload').click(function (e) {
e.preventDefault();
window.location = "/api/employees?format=csv";
});
在服务器上,MediaTypeMappings
必须通过添加一个构造函数来使用:
public EmployeeCsvFormatter(MediaTypeMapping mediaTypeMapping)
: this()
{
MediaTypeMappings.Add(mediaTypeMapping);
}
然后,将此格式化程序添加到 Web Api 配置中:
configuration.Formatters.Add(new EmployeeCsvFormatter
(new QueryStringMapping("format", "csv", "text/csv")));
关于c# - 如何使用 jQuery Ajax 调用从 ASP.NET Web Api 下载 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15334227/