多个流文件打包为ZIP
无需本地暂存文件,直接给流到前端
Controller
@PostMapping(value = "自己的请求地址")
public byte[] downlondResume(HttpServletResponse response,@RequestBody List<String> personIds) throws Exception {
byte[] responseEntity = personService.downloadAll(response, personIds);
String fileName = URLEncoder.encode("批量导出.zip", "UTF-8");
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
return responseEntity;
}
Service
byte[] downloadAll(HttpServletResponse response, List<String> personIds) throws ExecutionException, InterruptedException, Exception;
ServiceImp
@Override
public byte[] downloadAll(HttpServletResponse response, List<String> personIds) {
Map<String, byte[]> byteFileMap = new HashMap<>();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//自己的取流接口
batchFileToZIP(byteFileMap, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
public void batchFileToZIP(Map<String, byte[]> byteList, ByteArrayOutputStream byteOutPutStream) {
ZipOutputStream zipOutputStream = new ZipOutputStream(byteOutPutStream);
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();
}
}
}
大概流程就是这样,自己的是传的一组人员的id,根据人员的id进行数据的拼装
然后装到一个Map里面,设计为Map的key为传入人员的工号
value为传入人员的字节流