Tae*_*hin 136 c# asp.net-web-api
在我的ApiController类中,我有以下方法来下载服务器创建的文件.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
除了默认下载文件名是其id之外,一切都工作正常,因此用户可能每次都需要在另存为对话框时键入他/她自己的文件名.有没有办法在上面的代码中设置默认文件名?
Dar*_*rov 280
您需要在以下位置设置Content-Disposition
标题HttpResponseMessage
:
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(result);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "foo.txt"
};
Run Code Online (Sandbox Code Playgroud)
Kin*_*ake 26
编辑:正如评论中所提到的,我的答案没有考虑需要像a一样转义的字符;
.如果您的文件名可能包含分号,则应使用Darin所接受的答案.
添加Response.AddHeader以设置文件名
Response.AddHeader("Content-Disposition", "attachment; filename=*FILE_NAME*");
Run Code Online (Sandbox Code Playgroud)
只需将FILE_NAME更改为文件名即可.
如果要确保文件名已正确编码,但也避免使用WebApi HttpResponseMessage,则可以使用以下命令:
Response.AddHeader("Content-Disposition", new System.Net.Mime.ContentDisposition("attachment") { FileName = "foo.txt" }.ToString());
Run Code Online (Sandbox Code Playgroud)
您可以使用ContentDisposition或ContentDispositionHeaderValue.在任一实例上调用ToString将为您执行文件名编码.
我认为这可能对你有所帮助.
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName)
Run Code Online (Sandbox Code Playgroud)