springboot2.x对mongoDB的集成
springboot2.x对mongoDB的集成
需引入import com.mongodb.client.gridfs.model.GridFSFile;这个包
/**
- 1.文件上传:与springboot1.x一样
/
(只列出核心代码)
gridFsTemplate.store(file.getInputStream(),file.getOriginalFilename(),file.getContentType());
/
*2.下载
*/
gridFsTemplate.findOne(query)返回类型由GridFSDBFile改为GridFSFile导致的问题:文件下载时下面的代码不可用
GridFSDBFile gridFSDBFile = new GridFSDBFile();
gridFSDBFile.writeTo(response.getOutputStream())
解决办法:将GridFSFile转换为GridFsResource
转换类:
package com.example.myallprogram.modules;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.stereotype.Component;
@Component(“gridConfig”)
@Configuration
public class GridConfig {
@Autowired
private MongoDbFactory mongoDbFactory;
@Autowired
private GridFSBucket gridFSBucket;
@Bean
public GridFSBucket getGridFSBuckets() {
MongoDatabase db = mongoDbFactory.getDb();
return GridFSBuckets.create(db);
}
// 将GridFSFile 转成 GridFsResource
public GridFsResource convertGridFSFile2Resource(GridFSFile gridFsFile) {
GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFsFile.getObjectId());
return new GridFsResource(gridFsFile, gridFSDownloadStream);
}
}
下载方法:
@RequestMapping(value = “/downloadFile”,method = RequestMethod.GET)
public void downloadFile(@RequestParam(name = “fileName”) String fileName, HttpServletResponse response) throws Exception {
GridFSFile gridFSFile = gridFsTemplate.findOne(new Query().addCriteria(Criteria.where(“filename”).is(fileName)));
GridFsResource fsResource = gridConfig.convertGridFSFile2Resource(gridFSFile);
IOUtils.copy(fsResource.getInputStream(),response.getOutputStream());
}
/*
*3.删除
*删除时需要@ResponseBody注解
*/
@RequestMapping(value="/deleteFile",method = RequestMethod.POST)
@ResponseBody
public void deleteFromMongo(@RequestParam(name=“fileName”) String fileName){
gridFsTemplate.delete(Query.query(Criteria.where(“filename”).is(fileName)));
}
推荐阅读
-
Springboot2.X集成redis集群(Lettuce)连接的方法
-
C# 对MongoDB 进行增删改查的简单操作实例
-
Spring Boot集成Shiro并利用MongoDB做Session存储的方法详解
-
springboot Mongodb的集成与使用实例详解
-
Sprint Boot 集成MongoDB的操作方法
-
Node.js对MongoDB数据库实现模糊查询的方法
-
springboot2.x集成swagger的方法示例
-
springboot Mongodb的集成与使用实例详解
-
PHP对MongoDB[NoSQL]数据库的操作
-
财政部等三部门:对集成电路线宽小于65纳米的逻辑电路等免征进口关税