gpt4 book ai didi

c# - Content-Disposition header 中的 Unicode

转载 作者:可可西里 更新时间:2023-11-01 08:32:05 25 4
gpt4 key购买 nike

我正在使用在 HttpHandler child 中实现的 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();

当我在文件名字段中提供 'ß' 'ä' 'ö' 'ü' 'ó' 'ß' 'ä' 'ö' 'ü' 'ó' 时,它看起来与我的不一样在文件名中有它在 Firefox 中看起来不错。添加 EncodingType 和 charset 没有用。

在 ie 中它是 'ß''ä''ö''ü''ó''ß' 'ä''ö''ü'_'ó' 在 firefox 中它是 'ß' 'ä' 'ö' 'ü' 'ó' 'ß' 'ä ' '°' '°' '°'。

知道如何解决这个问题吗?

最佳答案

我遇到了类似的问题。你必须使用 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);

编辑

我更仔细地阅读了规范。首先RFC2183指出:

Current [RFC 2045] grammar restricts parameter values (and hence Content-Disposition filenames) to US-ASCII.

但后来我发现 [RFC 2045] 已过时,必须引用 RFC 2231 ,其中指出:

Asterisks ("*") are reused to providethe indicator that language andcharacter set information is presentand encoding is being used. A singlequote ("'") is used to delimit thecharacter set and language informationat the beginning of the parametervalue. Percent signs ("%") are used asthe encoding flag, which agrees withRFC 2047.

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

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

请注意,为了向后兼容,除了 filename* 之外,还包含了 filename。您也可以选择其他编码并相应地修改参数,但 UTF-8 涵盖了一切。

关于c# - Content-Disposition header 中的 Unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2543584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com