admin管理员组

文章数量:1530847

浏览器下载文件名与源不一致问题

最近项目里碰到下载文件名与原来不一致的问题。
比如说
原来是空格的,下载后变成了加号;原来是加号的,下载后变成空格。

问题代码

void defaultDownload(String id,String wjlxType,HttpServletResponse response){
        /**
         *to do.... 
        **/
        String fileName = attach.getFileOriName();
        try {
            //这里URLEncoder.encode(fileName, "utf-8")编码有问题
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("URLEncoder.encode(fileName, \"utf-8\")出错...",e);
            ExceptionUtil.throwRuntimeException("不支持的编码格式!");
            return;
        }
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("content-length", attach.getFileSize().toString());

        /**
         *to do.... 
        **/
    }

检查发现: java.URLEncoder url编码值,某些特殊字符 编码值 对应不了 目前主流浏览器 解析值

如空格:java.URLEncoder编码值为【%20】;实际浏览器解析空格对应的编码值应为【+】
如加号:java.URLEncoder不编码,值为【+】;实际浏览器解析空格对应的编码值应为【%2B】

解决:调整URL编码的使用工具为 com.sun.jndi.toolkit.url.UrlUtil

 UrlUtil.encode(fileName, "utf-8")

本文标签: 文件名浏览器