Home >Java >javaTutorial >Chinese file name of java download file is garbled
The problem arises:
Upload pictures with Chinese names, but the Chinese names cannot be displayed when downloaded.
As shown:
(Related video tutorial recommendation: java video tutorial)
Solution:
1. Sping-mvc.xml part code:
<!-- 上传文件的处理器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置默认编码 解决了上传文件名乱码的问题 --> <property name="defaultEncoding" value="utf-8"></property> <!-- 上传图片最大大小5M --> <property name="maxUploadSize" value="5242440"></property> </bean>
2. FileController.java Chinese file name acquisition code:
Get the browser format and control the file according to different browsers Name encoding format.
String userAgent = request.getHeader("User-Agent");//获取浏览器名(IE/Chome/firefox) if(userAgent.contains("MSIE")||userAgent.contains("Trident")) {//针对IE或IE为内核的浏览器 fileName=java.net.URLEncoder.encode(fileName,"UTF-8"); }else { fileName=new String(fileName.getBytes("UTF-8"),"ISO-8859-1");//谷歌控制版本 } headers.setContentDispositionFormData("attachment", fileName);// 默认下载文件名为原始文件名
Other browser control character formats: (details)
String userAgent = request.getHeader("User-Agent");//获取浏览器名(IE/Chome/firefox) if (userAgent.contains("firefox")) { fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器 } else if (userAgent.contains("MSIE")) { fileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器 }else if (userAgent.contains("CHROME")) { fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");// 谷歌 } headers.setContentDispositionFormData("attachment", fileName);// 默认下载文件名为原始文件名
Recommended related articles and tutorials: java introductory tutorial
The above is the detailed content of Chinese file name of java download file is garbled. For more information, please follow other related articles on the PHP Chinese website!