java文件下载时文件名在ie和firefox下面表现不一致问题

首先文件名是是以utf-8编码保存在数据库中,文件名暂定为"1_中文文件123.txt ",然后作如下处理来下载

response.setContentType("application/octet-stream;charset=UTF-8");
fileName=java.net.URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

此时在ie下面点击文件下载的时候能够正确显示中文名称"1_中文文件123.txt%0A ",但是文件名的结尾却出现%0A字符(个人猜测是结束符的 utf-8编码);但是此时在firefox下面却显示"1_%E4%B8%AD%E6%96%87%E6%96%87%E4%BB %B6123.txt%0A "
然后我又试了另一种方案

response.setContentType("application/octet-stream;charset=UTF-8");
fileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

 

此时在ie下面下载的时候弹chu的文件名是乱码;而在firefox下面却正确显示"1_中文文件123.txt "。

解决方案:

public String getFileName(String filename, HttpServletRequestWrapper reqw){
        String agent = reqw.getHeader("USER-AGENT");
        if(null != agent && -1 != agent.indexOf("MSIE")){
            filename = URLEncoder.encode(filename,"UTF8");
        }else if(null != agent && -1 != agent.indexOf("Mozilla")){
            filename = MimeUtility.encodeText(filename,"UTF8","B");
        }
        return filename;
}
 

你可能感兴趣的:(java,.net,浏览器,IE,firefox)