---
title: "下载中文文件名乱码问题"
author: "lam"
date: "2008-01-08T12:09:43Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2008-01-08T12:09:43Z"
id: 153949
url: "https://lam.iteye.com/blog/153949"
---

原来处理下载的代码如下：
response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
下载的程序里有了这句，一般在IE6的下载提示框上将正确显示文件的名字，无论是简体中文，还是日文。

一. 上面方式，也就是先用URLEncoder编码，当中文文字超过17个时，IE6 无法下载文件。
这是IE的bug，参见微软的知识库文章 KB816868 。
原因可能是因为ie在处理 Response Header 的时候，对header的长度限制在150字节左右。
而一个汉字编码成UTF-8是9个字节，那么17个字便是153个字节，所以便会报错。
微软提供了一个补丁。这个补丁需要先安装ie6 sp1。

二. 我尝试使用 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");
        /*
         * see http://support.microsoft.com/default.aspx?kbid=816868
         */
        if (fileName.length() > 150) {
            String guessCharset = xxxx /*根据request的locale 得出可能的编码，中文操作系统通常是gb2312*/
            fileName = new String(atta.getFileName().getBytes(guessCharset), "ISO8859-1");
        }
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        
暂且不考虑 Firefox。
/////////////////////

下面是解决文件名空格问题

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() > 150) {
                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;
    }