最近开发项目中,有个需求是批量下载文件,但网上看了很多案例,基本都是通过zip包压缩的方式进行下载
我在这里记录一下!
public ResponseEntity<byte[]> downloadAttachMent(@RequestParam String cInsAcNo,
HttpServletRequest request, HttpServletResponse response) throws IOException {
Map<String, byte[]> byteFileMap = new HashMap<>();
// 获取凭证信息
List<AttachmentVO> AttachmentVOList = insChaReconService.queryAttachmentByInsNo(cInsAcNo);
for (AttachmentVO attachmentVO:AttachmentVOList) {
String filePath = attachmentVO.getcFilePath();
File file = new File(filePath);
if (!file.exists()) {
logger.error("附件文件不存在:{}",filePath);
}else {
byteFileMap.put(file.getName(), FileUtils.readFileToByteArray(file));
}
}
ByteArrayOutputStream byteArrayOutputStream = ZipUtils.batchFileToZIP(byteFileMap);
String zipFileName = String.format("%s%s", LocalDateTime.now(), ".zip");
//return ResponseEntityUtils.buildByteFileResponse(zipFileName, byteArrayOutputStream.toByteArray(), response);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("fileName", zipFileName);
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(byteArrayOutputStream.toByteArray(),
headers, HttpStatus.OK);
logger.info("下载凭证成功");
return responseEntity;
工具类
package com.isoftstone.reconciliation.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtils {
/**
* @Author dongs
* @Description 文件批量压缩,不保存实际位置
* @Date 2021/4/23
* @Param [List<File>]
* @return
**/
public static ByteArrayOutputStream batchFileToZIP(Map<String, byte[]> byteList) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);
try {
for (Map.Entry<String, byte[]> entry : byteList.entrySet()) {
//写入一个条目,我们需要给这个条目起个名字,相当于起一个文件名称
zipOutputStream.putNextEntry(new ZipEntry(entry.getKey()));
zipOutputStream.write(entry.getValue());
}
zipOutputStream.closeEntry();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
zipOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return byteArrayOutputStream;
}
}
PostMan测试
