您的位置:首页 > 其它

解决上传文件时服务端中文文件名乱码问题

2017-10-24 14:25 597 查看
来源:http://blog.csdn.net/u011090495/article/details/18984683

form 表单 post 上传文件时服务端获取的中文文件名乱码,调试发现 request.getCharacterEncoding() 为 null。可是页面中我已经设置了文档编码了呀:

[java] view
plain copy

<!-- html 4 的编码设置方式 -->  

<meta http-equiv="content-type" content="text/html; charset=UTF-8">  

<!-- html 5 的编码设置方式 -->  

<meta charset="UTF-8">  

对文件名做了如下转码就得到原文件名了:

[java] view
plain copy

new String(multipartFile.getOriginalFilename().getBytes("ISO-8859-1"), "UTF-8");  

调试发现 spring mvc 内部如果 request.getCharacterEncoding() 为 null 就默认为 ISO-8859-1。

但为什么请求编码为空呢?google了哈,网络上有人说IE不会将页面上指定的编码写入http header发送给客户端,而我用的是chrome。

不管了,先求证哈此种说法,编写一个filter显式设置请求编码:

[java] view
plain copy

public class SetCharacterEncodingFilter implements Filter {  

    ...  

  

    @Override  

    public void doFilter(ServletRequest request, ServletResponse response,  

            FilterChain filterChain) throws IOException, ServletException {  

        if (request.getCharacterEncoding() == null) {  

            request.setCharacterEncoding("UTF-8");  

        }  

        filterChain.doFilter(request, response);  

    }  

      

    ...  

}  

再次测试,哦了,无需转码即可获取原本的中文文件名。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: