Spring mvc文件下载IE/Edge中文乱码解决
编程教程
>
Java
>
Spring
(2175)
2024-11-26 14:39:04
引言
在spring mvc项目开发中,我们可能经常遇到文件的上传和下载操作。这里将讲解在IE/Edge浏览器中文件下载中文乱码的解决方法。
一.解决spring mvc IE/Edge浏览器乱码
编写controller测试代码:
package net.xqlee.project.controller;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class FileController {
/**
* 文件下载
*
* @param request
* @param response
*/
@GetMapping("download.do")
public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
try {
String fileName = "中文测试.DAT";
response.getWriter().write("中文测试你好");
fileName = dealFileName(request, fileName);
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
} catch (Exception e) {
e.printStackTrace();// logger
}
}
/**
* 处理IE/Edge(win10)浏览器中文乱码
*
* @param request
* @param fileName
* @return
*/
public String dealFileName(HttpServletRequest request, String fileName) {
try {
String codeFileName = "";
String agent = request.getHeader("User-Agent");
if (agent == null) {
return fileName;
}
agent = agent.toUpperCase();
if (null == agent) {
codeFileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
} else if (-1 != agent.indexOf("MSIE") || -1 != agent.indexOf("TRIDENT") || -1 != agent.indexOf("EDGE")) {
codeFileName = URLEncoder.encode(fileName, "UTF-8");
} else {
codeFileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
}
return codeFileName;
} catch (Exception e) {
e.printStackTrace();// logger
return fileName;
}
}
}
注意观察上面的代码,解决乱码主要在dealFilename();这个方法中进行处理的。FileName进行get UTF8字符集是因为当前代码的编码格式为UTF-8如果是GBK则更改为GBK
二.测试IE/Edge浏览器中文乱码的解决
2.1启动刚才controller所在的项目。
2.2访问文件下载地址查看结果
文件下载地址为:http://localhost:8080/download.do
观察IE浏览器:
从上图可以看到中文已经正常显示。接下来测试win10的Edge浏览器:

从上图也能看到中午呢乱码问题已经得到解决。
http://blog.xqlee.com/article/323.html