多文件成压缩包下载
/**
- 根据附件ID 多文件压缩包下载
- @param
- @param response
- @param request
*/
@RequestMapping("/download")
public void download(@RequestParam Integer id, HttpServletResponse response,HttpServletRequest request){
FileZipVo fileZipVo = new FileZipVo();
fileZipVo.setId(id);
fileZipVo.setForm(SystemConstant.SFILE_TYPE_TWENTY_ONE);
zhgdFileService.fileZipDown(request,response,fileZipVo);
}
/**
* 附件下载(把模块下的所有文件打包下载)
* @param request
* @param response
* @param fileZipVo
*/
@Transactional
public void fileZipDown(HttpServletRequest request, HttpServletResponse response, FileZipVo fileZipVo){
// 1 响应头的设置
response.reset();
response.setCharacterEncoding(“utf-8”);
response.setContentType(“multipart/form-data”);
// 2 设置压缩包的名字 附件包 + 时间戳 + .zip
String billName = “附件包_” + System.currentTimeMillis() + “.zip”;
// 3 返回客户端浏览器的版本号、类型
String agent = request.getHeader(“USER-AGENT”);
try {
//针对IE或者以IE为内核的浏览器:
if (agent.contains(“MSIE”)||agent.contains(“Trident”)) {
billName = java.net.URLEncoder.encode(billName, “UTF-8”);
} else {
// 非IE浏览器的处理:
billName = new String(billName.getBytes(“UTF-8”),“ISO-8859-1”);
}
} catch (Exception e) {
e.printStackTrace();
}
response.setHeader(“Content-Disposition”, “attachment;fileName=”" + billName + “”");
// 4 设置压缩流:直接写入response,实现边压缩边下载
ZipOutputStream zipos = null;
try {
zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
zipos.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法
} catch (Exception e) {
e.printStackTrace();
}
// 5 循环将文件写入压缩流
DataOutputStream os = null;
// 6 查询数据库获取文件信息
LambdaQueryWrapper zhgdFileWrapper = new LambdaQueryWrapper<>();
zhgdFileWrapper.eq(ZhgdFile::getParentId, fileZipVo.getId());
zhgdFileWrapper.eq(ZhgdFile::getForm, fileZipVo.getForm());
List zhgdFileList = zhgdFileMapper.selectList(zhgdFileWrapper);
// 7 遍历文件信息(主要获取文件名/文件路径等)
if(CollectionUtils.isNotEmpty(zhgdFileList)){
for(ZhgdFile zhgdFile : zhgdFileList){
//文件路径
String filePath = zhgdFile.getFilePath();
File file = new File(filePath);
if (file.exists()) {
try {
//添加ZipEntry,并ZipEntry中写入文件流
String fileName = zhgdFile.getFileName();//.substring(0,authAttachmentDetail.getFileName().indexOf("."));
zipos.putNextEntry(new ZipEntry(fileName));
os = new DataOutputStream(zipos);
InputStream is = new FileInputStream(file);
byte[] b = new byte[100];
int length = 0;
while((length = is.read(b))!= -1){
os.write(b, 0, length);
}
is.close();
zipos.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//关闭流
try {
if(os != null){
os.flush();
os.close();
}
zipos.close();
} catch (IOException e) {
e.printStackTrace();
}
}