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

来源:互联网 发布:网页 卡片式 数据列表 编辑:程序博客网 时间:2024/05/11 23:03

来源:http://blog.csdn.net/u011090495/article/details/18984683

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

[java] view plain copy
  1. <!-- html 4 的编码设置方式 -->  
  2. <meta http-equiv="content-type" content="text/html; charset=UTF-8">  
  3. <!-- html 5 的编码设置方式 -->  
  4. <meta charset="UTF-8">  

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

[java] view plain copy
  1. 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
  1. public class SetCharacterEncodingFilter implements Filter {  
  2.     ...  
  3.   
  4.     @Override  
  5.     public void doFilter(ServletRequest request, ServletResponse response,  
  6.             FilterChain filterChain) throws IOException, ServletException {  
  7.         if (request.getCharacterEncoding() == null) {  
  8.             request.setCharacterEncoding("UTF-8");  
  9.         }  
  10.         filterChain.doFilter(request, response);  
  11.     }  
  12.       
  13.     ...  
  14. }  
再次测试,哦了,无需转码即可获取原本的中文文件名。
阅读全文
0 0
原创粉丝点击