假如程序猿们需要做一个批量把后台[本地/第三方]文件汇总在压缩包内并返回给前端下载,这里是一个测试成功的Demo,可以放心使用。
@RequestMapping(value = "/downloadZip", method = RequestMethod.GET)
public ResponseEntity<byte[]> downloadZip(@RequestBody DownloadVo downloadVo) {
return downloadService.downloadZip(downloadVo);
}
import java.nio.file.Path;
import java.io.File;
import java.io.ByteArrayOutStream;
import java.io.BufferedOutputStream;
import java.util.zip.ZipOutputStream;
poblic ResponseEntity<byte[]> downloadZip(DownloadVo downloadVo) throws IOException {
ByteArrayOutStream byteArrayOutStream = new ByteArrayOutStream();
try(BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutStream);
ZipOutputStream zos = new ZipOutputStream(bufferedOutputStream);){
List<DocumentList> docList = docDao.getDocumentListByParam(downloadVo);
for(DocumentList ele : docList) {
if(...){
byte[] document = getByteDocument(downloadVo);
populateDocumentToZip(zos,ele.getFileName,document);
} else (...) {
File targetFile = new File(ele.getFilePath);
if(!targetFile.exists()) {
continue;
}
Path path = targetFile.toPath();
populateDocumentToZip(zos,ele.getFileName,Files.readAllBytes(path);
}
}
}catch(IOException e) {
logger.info(e);
}finally {
byteArrayOutStream.close();
}
}
public void populateDocumentsToZip(ZipOutputSteam zos,String fileName, byte[] document) {
try{
zos.putNextEntry(new ZipEntry(fileName));
zos.write(document);
}catch(Exception e) {
logger.error(e);
}
}