我有一个Web Api函数,它返回文件流
[HttpPost]
public HttpResponseMessage DownloadDocument([FromBody] parameters)
{
try
{
var stream = FileHelper.GetFilesStream(fileUrl);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(stream) };
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition.FileName = fileName;
return result;
}
catch (Exception)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "File Not Found");
}
}
如何在Jquery Ajax中调用此方法以下载文件,以便弹出“保存文件”对话框。我正在使用tickout.js,在按钮的单击事件处理程序中,我调用了此WebAPI方法,并获得了流,但是我不知道如何将其保存到文件中。
您可以通过修改将数据发送到webapi的方式来解决此问题。
在您的Javascript中,您可以创建一个隐藏的表单并将所需的数据附加到该表单中,然后提交。
示例代码显示在coffeescript中,但应易于阅读/转换:
downloadDocument: (fileUri, otherProp, successCallback) =>
if $('#hidden-form').length > 0
$('#hidden-form').remove()
$('<form>').attr(
method: 'POST',
id: 'hidden-form',
action: '/your/url/to/method'
).appendTo('body');
$('<input>').attr({
type: 'hidden',
id: 'fileUri',
name: 'fileUri',
value: fileUri
}).appendTo('#hidden-form')
$('<input>').attr({
type: 'hidden',
id: 'otherProp',
name: 'otherProp',
value: otherProp
}).appendTo('#hidden-form')
$('#hidden-form').bind("submit", successCallback)
$('#hidden-form').submit()
然后,我还将创建一个DTO对象,该对象在您的webAPI控制器中作为参数接收,而不是从请求正文中读取:
public DownloadDocumentDTO
{
public string fileUri {get;set;}
public object otherProp {get;set;}
}
[HttpPost]
public HttpResponseMessage DownloadDocument(DownloadDocumentDTO _dto)
{
....
}
控制器方法中的代码应该没问题。应该注意的是,如果您试图传递更复杂的数据(由于未提及,因此不知道是否这样做),那么您将需要向隐藏的表单中添加更多的输入,它将无法传递对象向上。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句