关于中文文件下载的问题,网上的咨询和答疑已经很多,

我原来处理下载的代码如下:

response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));

下载的程序里有了这句,一般在IE6的下载提示框上将正确显示文件的名字,无论是简体中文,还是日文。不过当时确实没有仔细测试文件名很长的中文文件名。 先如今经过仔细测试,发现文字只要超过12个字,就不能下载了。经过好一番google和反复测试,总算对这个问题有了系统的认识,

分列如下: 一. 通过我原来的方式,也就是先用URLEncoder编码,当中文文字超过17个时,IE6 无法下载文件。这是IE的bug,参见微软的知识库文章 KB816868 。原因可能是因为ie在处理 Response Header 的时候,对header的长度限制在150字节左右。而一个汉字编码成UTF-8是9个字节,那么17个字便是108个字节,所以便会报错。微软提供了一个补丁,可以从 这里 下载。这个补丁需要先安装ie6 sp1。因为我平时勤打补丁,我的IE6版本号是 6.0.2800.1106.xpsp2_xxxxx。所以我可能已经安装过了补丁,从而可以下载,但仍然出现文件名被截断的现象。微软让我们等待IE下 一个service pack的发布。我今天也上网看到了好消息,迫于firefox的压力,IE7可能在年中发布。另外,Firefox 不支持这样的方式,将把编码后的%xx%xx直接作为文件名显示。

二. 我尝试使用 javamail 的MimeUtility.encode()方法来编码文件名,也就是编码成 =?gb2312?B?xxxxxxxx?= 这样的形式,并从 RFC1522 中找到对应的标准支持。不过很遗憾,IE6并不支持这一个标准。我试了一下,Firefox是支持的。

三. 按网上很多人提供的解决方案:将文件名编码成ISO8859-1似乎是有效的解决方案,代码如下: response.setHeader( "Content-Disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) ); 在确保附件文件名都是简 体中文字的情况下,那么这个办法确实是最有效的,不用让客户逐个的升级IE。如果台湾同胞用,把gb2312改成big5就行。但现在的系统通常都加入了 国际化的支持,普遍使用UTF-8。如果文件名中又有简体中文字,又有繁体中文,还有日文。那么乱码便产生了。另外,在我的电脑上Firefox (v1.0-en)下载也是乱码。

折中考虑,我结合了一、三的方式,

代码片断如下:

String fileName = URLEncoder.encode(atta.getFileName(), "UTF-8"); 
 if (fileName.length() > 100)
{ String guessCharset = xxxx /*根据request的locale 得出可能的编码,中文操作系统通常是gb2312*/
 fileName = new String(atta.getFileName().getBytes(guessCharset), "ISO8859-1"); 
}
 response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

下面是解决文件名空格问题

String fileName = StringUtils.trim(file.getName()); 
String formatFileName = encodingFileName(name);
//在后面定义方法encodingFileName(String fileName); 
response.setHeader("Content-Disposition", "attachment; filename=" + formatFileName ); 
//处理文件名中出现的空格 
//其中%20是空格在UTF-8下的编码 
public static String encodingFileName(String fileName) 
{ 
String returnFileName = "";
 try { 
returnFileName = URLEncoder.encode(fileName, "UTF-8"); 
returnFileName = StringUtils.replace(returnFileName, "+", "%20"); 
if (returnFileName.length() > 100) 
{ 
returnFileName = new String(fileName.getBytes("GB2312"), "ISO8859-1"); 
returnFileName = StringUtils.replace(returnFileName, " ", "%20"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); 
if (log.isWarnEnabled()) { log.info("Don't support this encoding ..."); } }
 return returnFileName; }