java下载英文文件成功,中文文件失败。中文乱码的问题

Alicia96 2020-02-27 03:14:24
后台代码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接收参数
String path = request.getParameter("filename");
System.out.println("path"+path);
if(path != null){
path = new String(path.getBytes("ISO-8859-1"),"UTF-8");
}
File file = new File(path);
//2.下载:设置两个头和一个流
// 获得文件名
String filename = file.getName();
System.out.println("filename1"+filename);
// 设置Content-Type
String type = getServletContext().getMimeType(filename);
response.setContentType(type);
// 判断浏览器类型
String agent = request.getHeader("User-Agent");

if(agent.contains("Firefox")){
//Firefox使用base64编码
filename = DownloadUtils.base64EncoderFileName(filename);
}else{
//IE或其他浏览器
filename = URLEncoder.encode(filename,"UTF-8");
filename = filename.replace("+", " ");

System.out.println("filename2"+filename);
}
// 设置Content-Disposition
response.setHeader("Content-Disposition", "attachment;filename="+filename);
// 设置一个代表文件的输入流
InputStream is = new FileInputStream(file);
OutputStream os = response.getOutputStream();
//3.两个流对接
int len = 0;
byte[] b = new byte[1024];
while((len = is.read(b)) != -1){
os.write(b, 0, len);
}
is.close();
}
前端
<%
Queue<File> queue = new LinkedList<File>();
File root = new File("F://upload");
queue.offer(root);
while(!queue.isEmpty()){
File file = queue.poll();
File[] files = file.listFiles();
for (File f : files) {
if(f.isFile()){
%>
<h4><a href="${ pageContext.request.contextPath }/DownloadListServlet?filename=<%= f.getCanonicalPath().replace("\\", "/") %>"><%= f.getName() %></a></h4>
<%
}else{
queue.offer(f);
}
}

}
%>

图片名称是:中文.jpg

此为控制台打印
path:F:/upload/1/11/中文.jpg
filename1:1??.jpg
filename2:2%3F%3F.jpg

此为浏览器
http://localhost:8080/web_test5/DownloadListServlet?filename=F:/upload/1/11/中文.jpg


报错
java.io.FileNotFoundException: F:\upload\1\11\??.jpg (文件名、目录名或卷标语法不正确。

尝试过先解码再编码也不行,还是乱码。下载英文文件成功,中文文件失败。
求助大佬!!这个中文乱码怎么解决
...全文
383 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Alicia96 2020-03-15
  • 打赏
  • 举报
回复
Alicia96 2020-03-06
  • 打赏
  • 举报
回复
Alicia96 2020-03-04
  • 打赏
  • 举报
回复
还是不行,还是乱码
  • 打赏
  • 举报
回复
不用判断浏览器类型,直接拿这名代码试试
filename = agent.toLowerCase().indexOf("msie") == -1 ? new String(filename .getBytes("UTF-8"), "ISO8859-1") : URLEncoder.encode(filename , "UTF-8");
Alicia96 2020-03-02
  • 打赏
  • 举报
回复
Alicia96 2020-02-28
  • 打赏
  • 举报
回复
求助大佬!!

50,504

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧