压缩工具-ZipUtil: https://www.bookstack.cn/read/hutool/a56da94bbb16617b.md (Hutool 参考文档)
//创建临时文件
File zipFile = File.createTempFile("test", ".zip");
Path temp = Files.createTempDirectory(null);
String srcImgPath = temp.toString();
for( 循环 ){
String outImgPath = srcImgPath + "/aa/bb/cc";
File outImgFile = new File(outImgPath);
//如果文件夹不存在则创建
if (!outImgFile.exists() && !outImgFile.isDirectory()) {
outImgFile.mkdirs();
}
FileOutputStream outImgStream = new FileOutputStream(outImgPath + "/" + name);
ImageIO.write(bufImg, imgSuffix, outImgStream);
outImgStream.flush();
outImgStream.close();
}
ZipUtil.zip(srcImgPath, zipFile.getAbsolutePath(), true);
String header = request.getHeader("User-Agent").toUpperCase();
String fileName = "附件信息" + System.currentTimeMillis() + ".zip";
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
fileName = URLEncoder.encode(fileName, "utf-8");
//IE下载文件名空格变+号问题
fileName = fileName.replace("+", "%20");
} else {
fileName = new String(fileName.getBytes(), "ISO8859-1");
}
response.reset();
response.setContentType("text/plain");
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Location", fileName);
response.setHeader("Cache-Control", "max-age=0");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
FileInputStream fis = new FileInputStream(zipFile);
BufferedInputStream buff = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
byte[] car = new byte[1024];
int l = 0;
while (l < zipFile.length()) {
int j = buff.read(car, 0, 1024);
l += j;
out.write(car, 0, j);
}
// 关闭流
fis.close();
buff.close();
out.close();
// 删除临时文件
zipFile.delete();
FileUtil.deleteDir(srcImgPath);