问题
I use the following code to send files from my server to the client:
Response.AppendHeader("content-disposition", "attachment; filename=" + FileName);
Response.ContentType = MimeType;
Response.WriteFile(PathToFile);
Response.End();
This works fine. Problem is, that when I download files from Internet Explorer, special characters, like the danish æ, ø and å, gets interpreted wrong. So i file with the name 'Test æ ø å file.txt' downloads as 'Test æ_ø_Ã¥ file.txt'
I´ve tried adding Byte Order Mark to the response:
byte[] BOM = { 0xEF, 0xBB, 0xBF };
Response.BinaryWrite(BOM);
And setting the charset:
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.UTF8;
But none if it helped. This seems only to be a problem in Internet Explorer.
回答1:
The headers doesn't use the encoding of the content, so it won't help to change the content encoding. There is a standard for specifying encoding for the header parameters, but it's pretty new, so it won't be fully supportred in all browsers:
http://greenbytes.de/tech/webdav/rfc5987.html
This is how you would encode the name:
string FileName = "Test æ ø å file.txt";
string name = String.Concat(Encoding.UTF8.GetBytes(FileName).Select(b => {
if ((b >= 48 && b <= 57) || (b >= 65 && b <= 90) || (b >= 97 && b <= 122)) {
return new String((char)b, 1);
} else {
return String.Format("%{0:x2}", b);
}
}).ToArray());
Response.AppendHeader("content-disposition", "attachment; filename*=UTF-8''" + name);
The text ending up in the header would look like this:
attachment; filename*=UTF-8''Test%20%c3%a6%20%c3%b8%20%c3%a5%20file%2etxt
Note: The code encodes all characters except alphanumeric. That works, but not all other characters need encoding. You could evolve the code to leave a few more characters unencoded, after checking the standards.
回答2:
Try to specify specific file type like below (this is for excel file types) -
Response.ContentType = "application/vnd.ms-excel";
See What content type to force download of text response?
回答3:
It's much easier to get around the Internet Explorer filename problem, you'll find the answer here
You have to HttpUtility.UrlPathEncode(yourFileName)
- as this will mess up filenames in other browser, you'll have to check if the browser (Request.Browser.Browser
) is Internet Explorer (IE until version 10, Internet Explorer from version 11).
来源:https://stackoverflow.com/questions/14434239/response-write-filename-encoding-wrong-in-internet-explorer