引用网上多例代码,也为了下次用得时候,能记住
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.10</version> </dependency>
/**
* 下载多个文件,打包下载
*
* @param response
*/
@GetMapping("/zip")
public void downloadMultiFileToMinIO(HttpServletResponse response, String filesData) throws Exception {
// 设置文件夹名称
List<FileInfo> list = JSON.parseArray(filesData, FileInfo.class);
if (list == null || list.size() <= 0) {
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("<script>alert('文件为空!')</script>");
response.getWriter().flush();
return;
}
//被压缩文件InputStream
InputStream[] files = new InputStream[list.size()];
//被压缩文件名称
String[] names = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
FileSystemResource file = new FileSystemResource(path + File.separator + list.get(i).getNewFileName());
if (!file.exists()) {
throw new MyException("文件不存在");
}
InputStream inputStream = file.getInputStream();
if (inputStream == null) {
continue;
}
// 赋值
files[i] = inputStream;
// 设置文件名字
names[i] = list.get(i).getFileName();
}
response.reset();
response.setCharacterEncoding("UTF-8");
/* 设置文件ContentType类型 */
response.setContentType("multipart/form-data");
// response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment;filename=" + (new Date().getTime()) + ".zip");
//多个文件压缩成压缩包
// response.setHeader("Content-type", "application-download");
ZipUtil.zip(response.getOutputStream(), names, files);
}