如何设置在ASP.NET MVC的Web API下载的文件名 [英] How to set downloading file name in ASP.NET MVC Web API
本文介绍了如何设置在ASP.NET MVC的Web API下载的文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我ApiController类中,我有以下的方法来下载由服务器创建的文件。
In my ApiController class, I have following method to download a file created by server.
public HttpResponseMessage Get(int id)
{
try
{
string dir = HttpContext.Current.Server.MapPath("~"); //location of the template file
Stream file = new MemoryStream();
Stream result = _service.GetMyForm(id, dir, file);
if (result == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
result.Position = 0;
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(result);
return response;
}
catch (IOException)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
}
一切工作完美的除了默认的下载文件名是其ID,因此用户可能在另存为对话框每次都输入他/她自己的文件名。有什么办法来设置在code默认文件名以上?
Everything is working perfect except that default downloading file name is its id so user might have to type his/her own file name at save as dialog each time. Is there any way to set a default file name in the code above?
推荐答案
您需要设置内容处置
头对的Htt presponseMessage
:
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(result);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "foo.txt"
};
这篇关于如何设置在ASP.NET MVC的Web API下载的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文