ZIP工具类:
@Slf4jpublic classZipUtils {/*** 将多个流转成zip文件输出
*@paramlistStream 文件流实体类对象
*@paramfileName zip包的名称
*@paramresponse
*@return
*/
public static boolean listStreamToZipStream(ListlistStream, String fileName, HttpServletResponse response) {boolean flag = false;
BufferedInputStream bis= null;
FileOutputStream fos= null;
ZipOutputStream zos= null;
OutputStream out= null;try{
out=response.getOutputStream();
response.reset();
response.setHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes("GB2312"), "ISO-8859-1"));
response.setHeader("Access-Control-Allow-Origin","*");
response.setContentType("application/octet-stream; charset=utf-8");
response.setCharacterEncoding("UTF-8");
zos= newZipOutputStream(out);byte[] bufs = new byte[1024 * 10];for(ZipDto zipDto : listStream) {
String streamfilename=zipDto.getName();//创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = newZipEntry(streamfilename);
zos.putNextEntry(zipEntry);//读取待压缩的文件并写进压缩包里
bis = new BufferedInputStream(zipDto.getInputstream(), 1024 * 10);int read = 0;while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
zos.write(bufs,0, read);
}
}
flag= true;
zos.close();
}catch(FileNotFoundException e) {
e.printStackTrace();throw newRuntimeException(e);
}catch(IOException e) {
e.printStackTrace();throw newRuntimeException(e);
}finally{//关闭流
try{if (null !=bis){
bis.close();
}if (null !=zos){
zos.close();
}if (null !=out){
out.close();
}
}catch(IOException e) {//e.printStackTrace();
log.error(e.getMessage());
}
}returnflag;
}
}
ZIP DTO实体类:
@Datapublic classZipDto {publicString name;publicInputStream inputstream;publicZipDto(String name, InputStream inputstream) {this.name =name;this.inputstream =inputstream;
}
}
ZIP 方法层:
public Boolean exportFile(List fileNames, HttpServletResponse response, HttpServletRequest request) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.in("file_name",fileNames);
List cmtDealerSpotplanManagements = list(queryWrapper);
// 将数据处理
List spotPlanNames = cmtDealerSpotplanManagements.stream().map(查询数据::getFilePath).collect(Collectors.toList());
List list = new ArrayList<>();
// 数据为空则返回
if ( CollectionUtils.isEmpty(spotPlanNames) ){
return false;
}
// 将数据地址去远程下载
for (String fileUrl : spotPlanNames){
File tempFile = new File(fileUrl);
String newFileUrl = fileUrl.replace(" ", "%20");
InputStream fileInputStream = fileService.download2(newFileUrl);
String tempFileName = tempFile.getName();
list.add(new ZipDto(tempFileName, fileInputStream));
}
String fileName = "test" + ".zip";
ZipUtils.listStreamToZipStream(list, fileName, response);
return true;
}