欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot2.x对mongoDB的集成

程序员文章站 2022-04-30 19:59:48
...

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)));
}