我正在研究如何从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文件?
发布于 2013-03-11 16:48:34
在没有Ajax using a simple form submit的情况下,jQuery Plugin for Requesting Ajax-like File Downloads做到了。
内部:
jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+inputs+'</form>')
.appendTo('body').submit().remove()
它有一个ajax风格的接口,所以在外部你可以这样调用它
$.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")));
发布于 2014-04-04 18:21:17
作为另一种方法,可以通过单击锚()或按钮提供下载,并将所请求的URL设置为响应附件的API方法。
在从System.Net.Http.Formatting.MediaTypeFormatter),派生的CsvMediaTypeFormatter
中,除了上面的答案中所示的映射文本/csv MIME类型之外,我发现需要做以下工作:
public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
{
base.SetDefaultContentHeaders(type, headers, mediaType);
headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = string.Concat("data", DateTime.UtcNow.ToString("yyyyMMddhhmmss"), ".csv")
};
headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
}
注意:写入流时,请设置Content-Length
头,并记得刷新流。我发现在没有调用Flush()
的情况下,返回的响应即使设置了正确的内容长度也无法成功返回客户端。
发布于 2013-06-06 04:34:41
您也可以通过修改xhr在beforeSend中设置请求头。
$.ajax({
url: "/api/employees",
type: "GET",
beforeSend: function (xhr) {
xhr.setRequestHeader("Accept", "text/csv");
},
success: function (data) {
}
});
https://stackoverflow.com/questions/15334227
复制相似问题