Springboot升级到2.x后gridFsTemplate.findOne(query)返回类型由GridFSDBFile改为GridFSFile导致的问题

问题描述:
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-iogroupId>
    <artifactId>commons-ioartifactId>
    <version>2.4version>
dependency>

你可能感兴趣的:(Java)