文件打包成zip后会下载到服务器上,下载完成后,可以通过固定路径去下载或者访问zip
@Override
public AjaxResult downloadZipSearch(QueryReportListBody body, HttpServletRequest request, HttpServletResponse response){
AjaxResult ajaxResult = AjaxResult.success();
FileOutputStream fos = null;
ZipOutputStream zos = null;
FileInputStream fis = null;
BufferedInputStream bis = null;
ReportGeneration dao = new ReportGeneration(body);
List<ReportGeneration> list = reportMapper.selectReportGenerationWebList(dao);
if(CollectionUtil.isEmpty(list)){
throw new CustomException("当前搜索条件无记录,请更换搜索条件。");
}
//文件前缀路径
String profile = RuoYiConfig.getProfile();
//设置压缩包的名字
String downloadName = "发电上报图片合集"+ Convert.toStr(SnowflakeIdWorker.getInstance().nextId()) +".zip";
ajaxResult.put("fileName",downloadName);
//zip下载后存放地址,注意,是放到服务器上的路径
String zippath = RuoYiConfig.getDownloadPath() + downloadName;
try {
fos = new FileOutputStream(zippath);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
Integer filenum = 0;
for(ReportGeneration report : list){
List<UniversalUploadFile> uufs = queryFiles(report.getReportId());
if(uufs == null || uufs.size() < 1){
continue;
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");
String star = formatter.format(report.getStartTime());
byte[] bytes = new byte[1024 * 10];
for(UniversalUploadFile item : uufs){
String fileName = item.getFileName();
String filePath = profile + item.getFilePath();
String funCode = item.getFunCode();
File file = new File(filePath);
if(!file.exists()){
continue;
}else{
//判断zip是否为空
filenum++;
}
funCode = PhotoConstant.FILE_NAME.get(funCode);
//压缩的文件名称,设置 / 将图片分文件夹
ZipEntry zipEntry = new ZipEntry( report.getSiteName() + "/" + star + "/" + funCode + fileName);
zos.putNextEntry(zipEntry);
//读取压缩文件并写入压缩包
fis = new FileInputStream(file.getPath());
bis = new BufferedInputStream(fis, 1024 * 10);
int read = 0;
while ((read = bis.read(bytes, 0, 1024 * 10)) != -1) {
zos.write(bytes, 0, read);
}
}
}
if(filenum == 0){
throw new CustomException("上报单文件都不存在,请刷新后重试。");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
// TODO: handle exception
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e);
} finally {
try {
if (zos != null) {
zos.flush();
zos.close();
}
if (fis != null) {
fis.close();
}
if (bis != null) {
bis.close();
}
if (fos != null) {
fos.flush();
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
// TODO: handle exception
}
}
return ajaxResult;
}