GridFS

GridFS介绍

GridFS是MongoDB提供的用于持久化存储文件的模块,CMS使用MongoDB存储数据,使用GridFS可以快速集成开发。

//缺点是效率没有那么高效..

 

工作原理的话我在百度找了一张图,

 

// 详细的话可以参考 https://docs.mongodb.com/manual/core/gridfs/

 

 

gridfs使用 - . -

存储文件

 
@Resource
GridFsTemplate gridFsTemplate;

@Test
    public void test2() throws FileNotFoundException {


        File file = new File("D:\\Code\\xuecheng\\XcEduCode\\testfreemark\\src\\main\\resources\\templates\\index_banner.ftl");

        //创建输入流
        FileInputStream inputStream = new FileInputStream(file);


        //向 gridtemplate 存储文件

        ObjectId objId = gridFsTemplate.store(inputStream, "轮播图测试文件", "");

        //id 转换成字符串格式
        String id = objId.toString();

        System.out.println(id);
//        5bfb661d4402c333342a9c6a
//        gridFsTemplate.store(, );
    }

 

查询文件

 

1. 需要配置一个bean,这个bean的作用是打开下载流文件

 

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MongoConfig {
    @Value("${spring.data.mongodb.database}")
    String db;
//
    @Bean
    public GridFSBucket getGridFSBucket(MongoClient mongoClient){
        MongoDatabase database = mongoClient.getDatabase(db);
        GridFSBucket bucket = GridFSBuckets.create(database);
        return bucket;
    }
}
  @Resource
    GridFSBucket gridFSBucket;
    //模板查询
    @Test
    public void fun02() throws IOException {

        String id = "5bfbad494402c33ad0b6dc05";
        GridFSFile fsFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)));

        //打开下载流文件
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(fsFile.getObjectId());


        //创建gridFsResource,用于获取流对象
        GridFsResource gridFsResource = new GridFsResource(fsFile, gridFSDownloadStream);

        //获取流中的数据
        String s = IOUtils.toString(gridFsResource.getInputStream(), "UTF‐8");

        System.out.println(s);
    }

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值