我的应用程序允许用户下载文件,但文件名可以采用西里尔字母的编码。 当用户下载文件,我想的名字是一样的用户看到,但在控制器ContentDisposition不允许在西里尔编码名称,我尝试将其转换为 UTF-8。 浏览器,IE和Opera下载使用正确的文件的文件名:
Firefox和Safari像这样的东西asp.net的MVC文件下载名称编码
我的控制器:
public ActionResult Download()
{
var name = Request.Params["Link"];
var filename = Request.Params["Name"];
filename = GetCleanedFileName(filename);
var cd = new ContentDisposition
{
FileName = filename,
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(name, "application/file");
}
public static string GetCleanedFileName(string s)
{
char[] chars = s.ToCharArray();
StringBuilder sb = new StringBuilder();
for (int index = 0; index < chars.Length; index++)
{
string encodedString = EncodeChar(chars[index]);
sb.Append(encodedString);
}
return sb.ToString();
}
private static string EncodeChar(char chr)
{
UTF8Encoding encoding = new UTF8Encoding();
StringBuilder sb = new StringBuilder();
byte[] bytes = encoding.GetBytes(chr.ToString());
for (int index = 0; index < bytes.Length; index++)
{
if (chr > 127)
sb.AppendFormat("%{0}", Convert.ToString(bytes[index], 16));
else
sb.AppendFormat("{0}", chr);
}
return sb.ToString();
}
的可能重复的[如何在HTTP内容处理标头的文件名参数编码?](http://stackoverflow.com/questions/93551/how-to-encode-the-filename-parameter-of-content -disposition集管中-HTTP)。在阅读这个重复问题中的答案之后,您将意识到问题的严重程度,并且可能会简单地将您的文件重命名为仅在其名称中使用ASCII字符。 –
不幸的是我无法重命名文件。 –
那么,祝你好运阅读说明书:http://greenbytes.de/tech/webdav/rfc5987.html哦,当然,如果你需要支持不符合本规范的浏览器,那么,你将不得不分别处理它们(并且针对您想要支持的每个浏览器和版本)。另一种可能性是将文档压缩成带有ASCII名称的.zip文件,您将流式传输到客户端,而其内部将是名称中包含任何字符的实际文档。 –