文件下载到服务器中
@Override
@DataScope
public AjaxResult downloadZipSearch(QueryReportListBody body){
AjaxResult ajaxResult = AjaxResult.success();
// 创建OSSClient实例。
//参数:endpoint,accessKeyId,secretAccessKey
OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessId(), ossConfig.getAccessKey());
FileOutputStream fos = null;
ZipOutputStream zos = null;
BufferedInputStream bis = null;
ReportGeneration dao = new ReportGeneration(body);
List<ReportGeneration> list = reportMapper.selectReportGenerationWebList(dao);
if(CollectionUtil.isEmpty(list)){
throw new CustomException("当前搜索条件无记录,请更换搜索条件。");
}
//设置压缩包的名字
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 = item.getFilePath();
String ossName = filePath.substring(0,1).equals("/") ? filePath.substring(1) : filePath;
String funCode = item.getFunCode();
//判断文件是否存在
boolean found = ossClient.doesObjectExist(ossConfig.getBucket(), ossName);
if(!found){
continue;
}else{
//判断zip是否为空
filenum++;
}
// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
OSSObject ossObject = ossClient.getObject(ossConfig.getBucket(), ossName);
//获取文件流
InputStream objectContent = ossObject.getObjectContent();
funCode = PhotoConstant.FILE_NAME.get(funCode);
//压缩的文件名称
ZipEntry zipEntry = new ZipEntry( report.getSiteName() + "/" + star + "/" + funCode + fileName);
zos.putNextEntry(zipEntry);
//读取压缩文件并写入压缩包
bis = new BufferedInputStream(objectContent, 1024 * 10);
int read = 0;
while ((read = bis.read(bytes, 0, 1024 * 10)) != -1) {
zos.write(bytes, 0, read);
}
// ossObject对象使用完毕后必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
ossObject.close();
}
}
if(filenum == 0){
throw new CustomException("上报单文件都不存在,请刷新后重试。");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
try {
if (zos != null) {
zos.flush();
zos.close();
}
if (bis != null) {
bis.close();
}
if (fos != null) {
fos.flush();
fos.close();
}
//关闭OSSClient实例
if (ossClient != null) {
ossClient.shutdown();
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
//返回文件名,后续可以在指定文件夹下操作文件
return ajaxResult;
}