下载JAVA文件时有两种情况下出现乱码:
1,下载时中文文件名乱码
2,由于该路径在下载过程中包含中文文件名乱码,因此提示找不到该文件
解决方案显示在下面的代码中
response.setContentType("multipart/form-data");
String userAgent= request.getHeader("User-Agent");
String oraFileName=meetingFile.getFileName();
String formFileName=oraFileName;//针对IE或者以IE为内核的浏览器:
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
formFileName= java.net.URLEncoder.encode(formFileName, "UTF-8");
}else{//非IE浏览器的处理:
formFileName = new String(formFileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-disposition",
String.format("attachment; filename=\"%s\"", formFileName));
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setCharacterEncoding("UTF-8");
ServletOutputStream out;//通过文件路径获得File对象
File file = null;if (meetingFile != null) {
file= new File(path + "upload/"+oraFileName);
}
(1)如果是第一种乱码,则下载页面遇到以下中文乱码问题
使用以下代码来解决
(2)如果下载遇到第二种乱码问题下载下来的文件名乱码下载下来的文件名乱码,如图所示:
使用以下代码解决: 首先,确保tomcat,eclipse等以UTF-8编码
然后在Java中,文件名编码与第一个分开,因此它们被分别编码而不会互相影响.
注意: 先前的测试可以解决下载Firefox和IE等浏览器时的编码问题,并且WIN10随附的浏览器仍会时不时出现乱码. 谢谢您与我分享.
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/shumachanpin/article-165105-1.html