需求:
下载文件,选择单个文档则下载单个文档,选择多个文档则讲多个文档压缩进一个压缩文件。
public ResponseEntity<InputStreamResource> downloadFiles(String literIds,String type) throws YMLibWebApplicationException {
Assert.notNull(literIds, "未指定要下载的文献");
if(null==type){
type="";
}
String[] ids = literIds.split(",");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
QFullTextLibrary qfullTextLibrary = QFullTextLibrary.fullTextLibrary;
Predicate predicate = qfullTextLibrary.id.in(ids);
Iterable<FullTextLibrary> iter = fullTextLibraryRepository.findAll(predicate);
int total = 0;
String fileName = "";
Collection<String> fileIds = new ArrayList<String>();
for (FullTextLibrary one : iter) {
String fileId = one.getFileId();
if (fileId != null && !fileId.equals("")) {
fileIds.add(fileId);
total++;
}
}
if (total > 1) {
fileName = DateUtils.date2String("yyyymmdd") + ".zip";
}
headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName));
long length = 0L;
Criteria cr = Criteria.where("_id").in(fileIds);
Query query = new Query(cr);
List<GridFSDBFile> files = gridFsOps.find(query);
if (!files.isEmpty()) {
if (files.size() == 1) {
GridFSDBFile file = files.get(0);
length = file.getLength();
return ResponseEntity.ok().contentLength(length).contentType(MediaType.APPLICATION_OCTET_STREAM)
.cacheControl(CacheControl.maxAge(3600, TimeUnit.SECONDS)).headers(headers)
.body(new InputStreamResource(file.getInputStream()));
} else {
long statr_time=System.currentTimeMillis();
try {
String zipfilePath = zipFilePath + fileName;
FileOutputStream outputStream = new FileOutputStream(zipfilePath);
ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(outputStream));
// zipOut.putNextEntry(new ZipEntry("/"));
for (GridFSDBFile file : files) {
length += file.getLength();
InputStream in = file.getInputStream();
String file_id=file.getId().toString();
zipOut.putNextEntry(new ZipEntry(file.getName()));
int j = 0;
byte[] buffer = new byte[1024*1024];
while ((j = in.read(buffer)) > 0) {
zipOut.write(buffer, 0, j);
}
// 关闭输入流
in.close();
}
zipOut.closeEntry();
zipOut.flush();
zipOut.close();
// 文件压缩成功
FileInputStream inputStream = new FileInputStream(zipfilePath);
long end_time=System.currentTimeMillis();
System.out.println(end_time-statr_time);
return ResponseEntity.ok().contentLength(length).contentType(MediaType.APPLICATION_OCTET_STREAM)
.headers(headers)
.body(new InputStreamResource(inputStream));
} catch (Exception e) {
log.error("压缩文件出错", e);
}
}
}
return null;
}
文件通过mongoid 去mongofs里面拿,拿出来后判断文件的个数,多个文件则进行压缩。代码如上图。