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

来源: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. }  
再次测试,哦了,无需转码即可获取原本的中文文件名。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值