ASP .NET使用日文文件名下载文件
-
07-07-2019 - |
题
我目前正在使用Visual Studio 2008作为我的ASP .NET应用程序。我试图通过Response对象服务器excel文件。问题是我似乎无法将文件的标题设置为日语。如果我将它设置为日文文件名,它将作为垃圾字符返回。我在日语WinXP中使用日语IE浏览器。
Response.AppendHeader("Content-Type", "application/vnd.ms-excel");
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=\"{0}\"", "日本語.xls"));
OR
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=\"{0}\"", Server.HtmlEncode("日本語.xls")));
我已经尝试将编码更改为Shift-JIS
Response.Charset = "Shift_JIS";
或
Response.Charset = "sjis";
有什么想法吗?顺便说一句,我也遇到了与Visual Studio 2005相同的问题。
解决方案
我不是ASP专家,但您是否尝试使用UrlEncode重新编码文件名?
Response.AddHeader("Content-Disposition",
System.Web.HttpUtility.UrlEncode(String.Format("attachment; filename=\"{0}\"", "日本語.xls")));
其他提示
我得到了它,最后......:)
使用 System.Web.HttpUtility.UrlPathEncode
解决了垃圾问题,但是当你打开文件时,它会在文件名中显示unicode-uncoded name而不是实际的日文字符。(嗯,这是在IE7和IE6中,UrlPathEncode与IE8一起工作正常。)
因此,您应该使用用于响应标头的编码来解码filname,而不是使用 System.Web.HttpUtility.UrlPathEncode
。
在.NET中,默认情况下,Response标头的编码为utf-8,将其更改为iso-8859-1。 修改web.config,如下所示,
<globalization responseHeaderEncoding="iso-8859-1" .../>
代码就是,
//apply Response header's encoding i.e. iso-8859-1 to the filename.
Dim fileName as String = "在庫あり全商品を24時間以内に出荷.doc"
Dim enc As Encoding = Encoding.GetEncoding("shift_jis")
Dim dec As Encoding = Encoding.GetEncoding("iso-8859-1")
fileName = dec.GetString(enc.GetBytes(fileName))
//Show Download Dialog box and Writting it on Client Side.
Response.ClearHeaders()
Response.ContentType = corspBean.ContentType
Response.AppendHeader("content-disposition", "attachment; filename=""" + fileName + """")
Response.BinaryWrite(bytes)
Response.End()
现在,更重要的是,我浪费了很多时间,因为它这在ASP.NET Development Server上不起作用即用于测试/调试Web的服务器本地计算机上的应用程序。因此,在IIS上部署解决方案并从那里进行测试。它在IIS上完美运行。 (并且IIS是每个ASP.NET应用程序的命运;)因此,无论它是否适用于ASP.NET Development Server都无关紧要)
不隶属于 StackOverflow