问题描述:
gridFsTemplate.findOne(query)
返回类型由GridFSDBFile
改为GridFSFile
导致的问题:文件下载时下面的代码不可用
GridFSDBFile gridFSDBFile = new GridFSDBFile();
gridFSDBFile.writeTo(response.getOutputStream())
解决方案:
1、将GridFSFile
转换为GridFsResource
public GridFsResource convertGridFSFile2Resource(GridFSFile gridFsFile) {
GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFsFile.getObjectId());
return new GridFsResource(gridFsFile, gridFSDownloadStream);
}
@Resource
private MongoDbFactory mongoDbFactory;
@Bean
public GridFSBucket getGridFSBuckets() {
MongoDatabase db = mongoDbFactory.getDb();
return GridFSBuckets.create(db);
}
@Resource
private GridFSBucket gridFSBucket;
2、Controller中响应代码改为:
IOUtils.copy(gridFsResource.getInputStream(), response.getOutputStream());
其他:IOUtils依赖 commons-io
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>