girdFS 存储照片,保存照片到硬盘

学习girdFS笔记,主要是girdFS存储照片到MongoDB·,保存照片到硬盘

0,GridFSBucket 配置类,用于打开下载流对象

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

1,存储照片

 @Autowired
    GridFsTemplate gridFsTemplate;

    @Autowired
    GridFSBucket gridFSBucket;

    @Test
    public void addImage() {
        try {
            //要存储的文件
            File file = new File("E:\\360Downloads\\1.jpg");
            //定义输入流
            FileInputStream inputStram = new FileInputStream(file);
            //向GridFS存储文件
            ObjectId objectId = gridFsTemplate.store(inputStram, "img测试");
            //得到文件ID
            String fileId = objectId.toString();
            System.out.println(fileId);//5d7e000fd3e38128a8481c4f
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

2, 下载图片

    @Test
    public void getImg() throws IOException {
        //获取id值
        String fileId = "5d7e000fd3e38128a8481c4f";
        //取出文件
        GridFSFile gridFSFile = gridFsTemplate.findOne(query(Criteria.where("_id").is(fileId)));
       
        //打开下载流对象(方式1)
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //创建gridFsResource,用于获取流对象
        GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
        
        /**打开下载流对象(方式2)
         GridFsResource resource = gridFsTemplate.getResource(gridFSFile);*/
      
        //获取输入流
        InputStream fis = gridFsResource.getInputStream();
        //获取输出流
        FileOutputStream fos=new FileOutputStream("d:\\4.jpg");

        byte[] bytes=new byte[1024];
        int len=0;
        while ((len=fis.read(bytes))!=-1){
            fos.write(bytes,0,len);
        }
        fos.close();
        fis.close();
    }

你可能感兴趣的:(gridFS)