来源:http://blog.csdn.net/u011090495/article/details/18984683
form 表单 post 上传文件时服务端获取的中文文件名乱码,调试发现 request.getCharacterEncoding() 为 null。可是页面中我已经设置了文档编码了呀:
- <!-- html 4 的编码设置方式 -->
- <meta http-equiv="content-type" content="text/html; charset=UTF-8">
- <!-- html 5 的编码设置方式 -->
- <meta charset="UTF-8">
对文件名做了如下转码就得到原文件名了:
- new String(multipartFile.getOriginalFilename().getBytes("ISO-8859-1"), "UTF-8");
调试发现 spring mvc 内部如果 request.getCharacterEncoding() 为 null 就默认为 ISO-8859-1。
但为什么请求编码为空呢?google了哈,网络上有人说IE不会将页面上指定的编码写入http header发送给客户端,而我用的是chrome。
不管了,先求证哈此种说法,编写一个filter显式设置请求编码:
- 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);
- }
-
- ...
- }
再次测试,哦了,无需转码即可获取原本的中文文件名。