我已经编写了一个休息服务来下载zip文件,但是问题是当没有文件存在时,该服务会下载一个空的zip文件。由于客户要求,我们无法禁用下载zip按钮表单UI。请帮我解决这个问题。 以下是我用于服务和控制器的代码
public Optional<ZipOutputStream> zippedOutFiles(DownloadZipDTO downloadZipDTO, ServletOutputStream outputStream)
throws IOException {
StringBuilder fileLocationBuilder = new StringBuilder();
int fileSize = 0;
ZipOutputStream zippedOut = new ZipOutputStream(outputStream);
Map<String, Integer> fileMap = new HashMap<>();
LOGGER.info(" Inside download zip service zippedOutFiles ");
for (DownloadZipEntityDTO files : downloadZipDTO.getDownloadZipEntityList()) {
fileSize = fileSize + files.getFileSize();
fileLocationBuilder.setLength(0);
fileLocationBuilder.append(files.getFileLocation());
Resource resource = new FileSystemResource(new File(fileLocationBuilder.toString()));
if (resource.exists()) {
checkDuplicateFiles(resource, fileMap);
ZipEntry entry = fileMap.get(resource.getFilename()) > 0
? new ZipEntry(resource.getFilename().substring(0, resource.getFilename().lastIndexOf('.'))
+ "_" + fileMap.get(resource.getFilename()).toString()
+ resource.getFilename().substring(resource.getFilename().lastIndexOf('.')))
: new ZipEntry(resource.getFilename());
entry.setSize(resource.contentLength());
entry.setTime(System.currentTimeMillis());
zippedOut.putNextEntry(entry);
StreamUtils.copy(resource.getInputStream(), zippedOut);
zippedOut.closeEntry();
} else {
zippedOut.finish();
zippedOut.close();
throw new Exception(" No file to zip");
}
}
zippedOut.finish();
zippedOut.close();
if ((fileSize) / 1024 > CasperProperties.getMaxFileUploadSize()) {
LOGGER.warn("Total file size is exceeded ", fileSize);
}
return Optional.of(zippedOut);
}
Controller:
Optional<ZipOutputStream> zippedOut = downloadZipService.zippedOutFiles(downloadZipDTO,
httpResponse.getOutputStream());
if (zippedOut.isPresent()) {
LOGGER.info("Inside submission Download zip controller setting response data");
serviceResponse.setResponseData(zippedOut);
String zippedOutName = (dcCodeID).toString().concat("_").concat("Submission")
.concat(CasperUtils.getDateFormatInString(new Date()));
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + zippedOutName + "\"")
.body(serviceResponse);
} else {
return ResponseEntity.noContent().build();
}
}