springboot mongoDB依赖:org.springframework.boot:spring-boot-starter-data-mongodb
private Document buildDocument(String fileName, String pictureGuid) {
Document document = new Document();
document.append("Ext", "");
document.append("SourceID", pictureGuid);
document.append("OriginFileName", fileName);
return document;
}
上传文件:
Document document = buildDocument(fileName, pictureGuid);
gridFsTemplate.store(file.getInputStream(), pictureGuid, file.getContentType(), document);
下载文件:
GridFSFindIterable gridFSFiles = gridFsTemplate.find(Query.query(Criteria.where("filename").is(pictureGuid)));
GridFSFile gridFSFile = gridFSFiles.first();
if (CheckUtils.isEmpty(gridFSFile)) {
return;
}
//打开一个下载流对象
GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
//创建gridFsResource,用于获取流对象
GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
byte[] data = IOUtils.toByteArray(gridFsResource.getInputStream());