Content-Disposition标头中的Unicode

Ran*_*eet 11 .net c# content-disposition http-headers

我正在使用在HttpHandler子项中实现的HttpContext对象来下载文件,当我在文件名中有非ascii字符时,它在IE中看起来很奇怪,而在Firefox中看起来很好.

以下是代码: -

       context.Response.ContentType = ".cs";
context.Response.AppendHeader("Content-Length", data.Length.ToString());
context.Response.AppendHeader("Content-Disposition", String.Format("attachment; filename={0}",filename));
        context.Response.OutputStream.Write(data, 0, data.Length);

context.Response.Flush();
Run Code Online (Sandbox Code Playgroud)

当我在文件名称字段中提供"嗯""澶'Ã'那张"A 3""嗯""澶'Ã'那张"A 3"它看起来比不同我有什么文件在Firefox中看起来很好看.添加EncodingType和charset一直没用.

在IE中它是'ÃÂ' 'ä' 'ÃÂ' 'ü' 'ó' 'ÃÂ' 'ä' 'ÃÂ' 'ü' _ 'ó',并在Firefox是'嗯'" Ã''''''''''''''''''''''''''''''''''''''''''''''''

任何想法如何解决这个问题?

Ser*_*jev 20

我有类似的问题.您必须使用HttpUtility.UrlEncodeServer.UrlEncode来编码文件名.另外我记得firefox不需要它.此外,当它是url编码时,它会破坏文件名.我的代码:

// IE needs url encoding, FF doesn't support it, Google Chrome doesn't care
if (Request.Browser.IsBrowser ("IE"))
{
    fileName = Server.UrlEncode(fileName);
}

Response.Clear ();
Response.AddHeader ("content-disposition", String.Format ("attachment;filename=\"{0}\"", fileName));
Response.AddHeader ("Content-Length", data.Length.ToString (CultureInfo.InvariantCulture));
Response.ContentType = mimeType;
Response.BinaryWrite(data);
Run Code Online (Sandbox Code Playgroud)

编辑

我已经仔细阅读了规范.首先,RFC2183声明:

当前[RFC 2045]语法将参数值(以及因此内容处理文件名)限制为US-ASCII.

但后来我发现[RFC 2045]已过时的参考资料,必须参考RFC 2231,其中规定:

重复使用星号("*")来提供语言和字符集信息存在以及正在使用编码的指示符.单引号("'")用于在参数值的开头界定字符集和语言信息.百分号("%")用作编码标志,与RFC 2047一致.

这意味着您可以将UrlEncode用于非ascii符号,只要您包含rfc中所述的编码即可.这是一个例子:

string.Format("attachment; filename=\"{0}\"; filename*=UTF-8''{0}", Server.UrlEncode(fileName, Encoding.UTF8));
Run Code Online (Sandbox Code Playgroud)

注意,filename除了filename*向后兼容性之外,还包括它.您也可以选择其他编码并相应地修改参数,但UTF-8涵盖了所有内容.


小智 9

HttpUtility.UrlPathEncode可能是更好的选择.由于URLEncode将用'+'符号替换空格.


Joh*_*yer 5

对我来说,这个解决方案适用于所有主要浏览器:

Response.AppendHeader("Content-Disposition", string.Format("attachment; filename*=UTF-8''{0}", HttpUtility.UrlPathEncode(fileName).Replace(",", "%2C"));
var mime = MimeMapping.GetMimeMapping(fileName);
return File(fileName, mime);
Run Code Online (Sandbox Code Playgroud)

使用 ASP.NET MVC 3。

替换是必要的,因为 Chrome 不喜欢参数值中的逗号 (,):http : //www.gangarasa.com/lets-Do-GoodCode/tag/err_response_headers_multiple_content_disposition/