Reputation: 1452
My application allow users to download files, but names of files can be in cyrillic encoding.
When user downloads file i want name to be like user see, but in controller ContentDisposition doesn't allow name in cyrillic encoding, and i try to convert it to
utf-8.
Chrome, IE and opera downloads file with correct name:
firefox and safari with something like this
my controller:
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();
}
Upvotes: 2
Views: 6079
Reputation: 8166
Look here, we used this as an example to return the filename that we wished when downloading files through a controller.
http://www.simple-talk.com/dotnet/asp.net/asp.net-mvc-action-results-and-pdf-content/
The FileResult has a FileDownloadName property that you can set that it uses to set the Filename as it's sent to the Response when the user downloads it.
Upvotes: 1