How do I encode a file name for download?

2019-03-09 20:57发布

When the file name is "Algunas MARCAS que nos acompañan" ASP.NET MVC raise an System.FormatException when I try to download that file. But if the file name is "Asistente de Gerencia Comercial" it doesn't.

I guess this is because something related to UTF-8 encoding, but I don't know how to encode that string.

If I'm right, how can I encode the string in UTF-8 encoding? If I'm not right, what is my problem?

7条回答
Viruses.
2楼-- · 2019-03-09 21:29

instead of using httpUtility that replaces the spaces in the file name with "+" using the following code resolve the problem:

string attachment = String.Format("attachment; filename={0}",Server.UrlPathEncode(file.Name.TrimEnd()));
Response.AddHeader("Content-Disposition", attachment);

please note that if you retrieve file name from data set you may need trim the name first! you have to also add the following lines of code in advance:

Response.Charset = "utf-8";
Response.HeaderEncoding = UnicodeEncoding.UTF8;
Response.ContentEncoding = UnicodeEncoding.UTF8;
查看更多
登录 后发表回答