在使用 java 流下载文件的时候,文件名称如果是中文,出现乱码的情况。解决办法:
FileName 使用 “ISO-8859-1” 编码。
public static void downloadZip(File file, HttpServletResponse response) {
try {
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
String fileName = new String(file.getName().getBytes(), "ISO-8859-1"); // 压缩包中文名称,不然乱码
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
toClient.write(buffer);
toClient.flush();
toClient.close();
//file.delete(); //将生成的服务器端文件删除
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
本文介绍了一种解决在Java中通过流下载带有中文名称的文件时出现乱码的方法。核心技巧在于使用ISO-8859-1编码处理文件名,确保在不同浏览器和操作系统间正确显示。
2671

被折叠的 条评论
为什么被折叠?



