批量下載檔案,將檔案打包成壓縮檔案
阿新 • • 發佈:2019-01-04
批量壓縮檔案
public static byte[] zipFiles(List<File> listfiles) throws IOException { byte[] buf = new byte[1024]; ByteArrayOutputStream outPut = new ByteArrayOutputStream(); ZipOutputStream out = new ZipOutputStream(outPut); List<String> nameList = new ArrayList<>(); for (File file : listfiles) { InputStream input = new ByteArrayInputStream(file.getContent()); if (nameList.size() > 0 && CommonUtil.existsStrList(nameList, file.getFileName())) { out.putNextEntry(new ZipEntry(CommonUtil.returnChangeFileName(file.getFileName(), nameList.size()))); } else { nameList.add(file.getFileName()); out.putNextEntry(new ZipEntry(file.getFileName())); } int len; while ((len = input.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); input.close(); } out.close(); return outPut.toByteArray(); }
輸出壓縮後的檔案
public Message downloadAll(Message msg) throws IOException { Message m = new Message(); FileDto dto = getParamBean(msg, FileDto.class); // idList 為file的idlist List<File> list = fileService.getFileList(dto.getFileIdList()); byte[] byteInfo = null; if (list != null) { byteInfo = ZIPUtils.zipFiles(list); } String fileName = new String((CommonUtil.uuid() + ".zip").getBytes("UTF-8"), "ISO-8859-1"); m.setBody(byteInfo); m.setStatus(HttpStatus.HTTP_OK); m.setHead(Message.CONTENT_LENGTH, byteInfo.length + ""); m.setHead("Content-Disposition", "attachment;filename=\"" + fileName + "\""); return m; }