jsp页面通过超链标签下载文件,文件名包含中文时,下载乱码,英文和数字可以正常下载,根据网上的方法试了很多次还是解决不了,困扰一天了,现在是凌晨1点这个问题搞得我睡不着,各位老哥帮小弟看看是
哪里错了页面编码设置utf_8
下载链接
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
EbizCompany company = (EbizCompany) request.getSession().getAttribute("currentCompany");
//String file = new String(request.getParameter("file").getBytes("ISO-8859-1"),"UTF-8");
String fileName = request.getParameter("file"); //客户端传递的需要下载的文件名
fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");
System.out.println("filename "+fileName);
//获得请求头中的User-Agent
String agent = request.getHeader("User-Agent");
//根据不同浏览器进行不同的编码
String fileNameEncoder = "";
if (agent.contains("MSIE")) {
// IE浏览器
fileNameEncoder = URLEncoder.encode(fileName, "utf-8");
fileNameEncoder = fileNameEncoder.replace("+", " ");
} else if (agent.contains("Firefox")) {
// 火狐浏览器
BASE64Encoder base64Encoder = new BASE64Encoder();
fileNameEncoder = "=?utf-8?B?" + base64Encoder.encode(fileName.getBytes("utf-8")) + "?=";
} else {
// 其它浏览器
fileNameEncoder = URLEncoder.encode(fileName, "utf-8");
}
//客户端通过文件的MIME区分下载的文件的类型
response.setContentType(this.getServletContext().getMimeType(fileName));
//告诉客户端不要直接解析该文件,而是以附件的形式打开(下载) 客户端默认对名字进行解码
response.setHeader("Content-Disposition", "attachment;filename=" + fileNameEncoder);
String time=Integer.toString(GeneralMethod.getYear(System.currentTimeMillis()))+"\\"+Integer.toString(GeneralMethod.getMonth(System.currentTimeMillis()));
String path = Constant.FilePath + "\\" + company.companyName+"\\"+time+"\\"+fileName;
FileInputStream fis = new FileInputStream(path);
response.setContentType("multipart/form-data");
ServletOutputStream out = response.getOutputStream();
byte[] bt = new byte[1024];
int length = 0;
while((length=fis.read(bt))!=-1){
out.write(bt,0,length);
}
out.close();
}
``` ![图片说明](https://img-ask.csdn.net/upload/201907/10/1562692854_226734.png)