ZIP工具類:
@Slf4j public class ZipUtils { /** * 將多個流轉成zip文件輸出 * @param listStream 文件流實體類對象 * @param fileName zip包的名稱 * @param response * @return */ public static boolean listStreamToZipStream(List<ZipDto> listStream, 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 = new ZipOutputStream(out); byte[] bufs = new byte[1024 * 10]; for (ZipDto zipDto : listStream) { String streamfilename = zipDto.getName(); // 創建ZIP實體,並添加進壓縮包 ZipEntry zipEntry = new ZipEntry(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 new RuntimeException(e); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(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()); } } return flag; } }
ZIP DTO實體類:
@Data public class ZipDto { public String name; public InputStream inputstream; public ZipDto(String name, InputStream inputstream) { this.name = name; this.inputstream = inputstream; } }
ZIP 方法層:
public Boolean exportFile(List<String> fileNames, HttpServletResponse response, HttpServletRequest request) {
QueryWrapper<查詢數據> queryWrapper = new QueryWrapper();
queryWrapper.in("file_name",fileNames);
List<查詢數據> cmtDealerSpotplanManagements = list(queryWrapper);
// 將數據處理
List<String> spotPlanNames = cmtDealerSpotplanManagements.stream().map(查詢數據::getFilePath).collect(Collectors.toList());
List<ZipDto> 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;
}