简体   繁体   English

如何在 ASP.NET Web API 中设置下载文件名

[英]How to set downloading file name in ASP.NET Web API

In my ApiController class, I have following method to download a file created by server.在我的 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);
    }
}

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.一切正常,除了默认下载文件名是其 id,因此用户可能必须每次在另存为对话框时键入他/她自己的文件名。 Is there any way to set a default file name in the code above?有没有办法在上面的代码中设置默认文件名?

You need to set the Content-Disposition header on the HttpResponseMessage :您需要在HttpResponseMessage上设置Content-Disposition标头:

HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(result);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "foo.txt"
};

EDIT: As mentioned in a comment, My answer doesn't account for characters that need to be escaped like a ;编辑:正如评论中提到的,我的回答没有考虑需要像;这样转义的字符; . . You should use the accepted answer Darin made if your file name could contain a semi-colon.如果您的文件名可以包含分号,您应该使用 Darin 提出的已接受答案。

Add a Response.AddHeader to set the file name添加一个 Response.AddHeader 来设置文件名

Response.AddHeader("Content-Disposition", "attachment; filename=*FILE_NAME*");

Just change FILE_NAME to the name of the file.只需将 FILE_NAME 更改为文件名即可。

If you want to ensure that the file name is properly encoded but also avoid the WebApi HttpResponseMessage you can use the following:如果您想确保文件名正确编码,但又要避免 WebApi HttpResponseMessage,您可以使用以下内容:

Response.AddHeader("Content-Disposition", new System.Net.Mime.ContentDisposition("attachment") { FileName = "foo.txt" }.ToString());

You may use either ContentDisposition or ContentDispositionHeaderValue.您可以使用 ContentDisposition 或 ContentDispositionHeaderValue。 Calling ToString on an instance of either will do the encoding of file names for you.在任一实例上调用 ToString 将为您编码文件名。

我认为这可能对您有所帮助。

Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName)

You need to add the content-disposition header to the response:您需要将 content-disposition 标头添加到响应中:

 response.StatusCode = HttpStatusCode.OK;
 response.Content = new StreamContent(result);
 response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
 return response;

If you are using ASP.NET Core MVC, the answers above are ever so slightly altered...如果您使用的是 ASP.NET Core MVC,上面的答案会略有改变......

In my action method (which returns async Task<JsonResult> ) I add the line (anywhere before the return statement):在我的操作方法(返回async Task<JsonResult> )中,我添加了以下行(在 return 语句之前的任何位置):

Response.Headers.Add("Content-Disposition", $"attachment; filename={myFileName}");

这应该做:

Response.AddHeader("Content-Disposition", "attachment;filename="+ YourFilename)

Note: The last line is mandatory.注意:最后一行是必填的。

If we didn't specify Access-Control-Expose-Headers , we will not get File Name in UI.如果我们没有指定Access-Control-Expose-Headers ,我们将不会在 UI 中获取文件名。

FileInfo file = new FileInfo(FILEPATH);

HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = file.Name
};
response.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

Considering the previous answers, it is necessary to be careful with globalized characters.考虑到前面的答案,有必要小心使用全球化字符。

Suppose the name of the file is: " Esdrújula prenda ñame - güena.jpg "假设文件名是:“ Esdrújula prenda ñame - güena.jpg

Raw result to download: "Esdrújula prenda ñame - güena.jpg" [Ugly]要下载的原始结果:“Esdrújula prenda ñame - güena.jpg”[丑陋]

HtmlEncode result to download: "Esdr&_250;jula prenda &_241;ame - g&_252;ena.jpg" [Ugly] HtmlEncode结果下载:“Esdr&_250;jula prenda &_241;ame - g&_252;ena.jpg”【丑】

UrlEncode result to download: " Esdrújula+prenda+ñame+-+güena.jpg " [OK] UrlEncode下载结果:“ Esdrújula+prenda+ñame+-+güena.jpg ” [OK]

Then, you need almost always to use the UrlEncode over the file name .然后,您几乎总是需要在文件名上使用 UrlEncode Moreover, if you set the content-disposition header as direct string, then you need to ensure surround with quotes to avoid browser compatibility issues.此外,如果您将 content-disposition 标头设置为直接字符串,那么您需要确保用引号引起来以避免浏览器兼容性问题。

Response.AddHeader("Content-Disposition", $"attachment; filename=\"{HttpUtility.UrlEncode(YourFilename)}\"");

or with class aid:或在课堂帮助下:

var cd = new ContentDisposition("attachment") { FileName = HttpUtility.UrlEncode(resultFileName) };
Response.AddHeader("Content-Disposition", cd.ToString());

The System.Net.Mime. System.Net.Mime。 ContentDisposition class takes care of quotes. ContentDisposition类负责引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM