public void downloadFileBatch(String[] filePaths, HttpServletResponse response){
try {
// 创建 ZipOutputStream
ZipOutputStream zipOutputStream = null;
// 创建 FileInputStream 对象
FileInputStream fileInputStream = null;
// 实例化 ZipOutputStream 对象
zipOutputStream = new ZipOutputStream(response.getOutputStream());
// 创建 ZipEntry 对象
ZipEntry zipEntry = null;
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName='aaa.zip'");
for (String filePath: filePaths){
File file = new File(filePath);
if (!file.exists()) {
return;
}
// 将源文件数组中的当前文件读入 FileInputStream 流中
fileInputStream = new FileInputStream(file);
// 实例化 ZipEntry 对象,源文件数组中的当前文件
zipEntry = new ZipEntry(file.getName());
zipOutputStream.putNextEntry(zipEntry);
// 该变量记录每次真正读的字节个数
int len;
// 定义每次读取的字节数组
byte[] buffer = new byte[1024];
while ((len = fileInputStream.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, len);
}
}
zipOutputStream.closeEntry();
zipOutputStream.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
java 文件压缩zip到前端下载
最新推荐文章于 2024-09-17 21:18:51 发布
本文介绍了一个Java方法,用于将多个文件批量打包为ZIP格式并提供下载。通过使用ZipOutputStream和FileInputStream,该方法可以将指定路径下的文件逐一读取并压缩,最终返回给用户。

1354

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



