Mongodb-GridFS 文件存储

本文介绍如何使用Java操作MongoDB的GridFS存储系统,详细讲解GridfsTest.java代码示例,涵盖文件上传、下载及管理操作。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

 GridfsTest.java

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class GridfsTest {

    @Autowired
    private  GridFsTemplate gridFsTemplate;
    @Autowired
    private GridFSBucket gridFSBucket;

    @Test
    public void uploadFile() throws FileNotFoundException {
        String pdfPath = "D:\\pdfRender\\古代埃及文明 封面.pdf";
        File file = new File(pdfPath);
        // 获得提交的文件名
        String fileName = file.getName();
        // 获得文件输入流
        InputStream ins = new FileInputStream(file);
        // 获得文件类型
        String contentType = "pdf";
        // 将文件存储到mongodb中,mongodb 将会返回这个文件的具体信息
        ObjectId objectId = gridFsTemplate.store(ins, fileName, contentType);
    }

    @Test
    public void download() throws IOException {
        String id="5eeb4bdfa610dd4b54583265";
        String md5="f3976c520026d2287c3746f4bc84f91e";
        //根据id查询文件
        GridFSFile gridFSFile =
                gridFsTemplate.findOne(Query.query(Criteria.where("md5").is(md5)));
        //打开流下载对象
        GridFSDownloadStream downloadStream =
                gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //获取流对象
        GridFsResource gridFsResource=new GridFsResource(gridFSFile,downloadStream);

        String pdfPath = "D:\\pdfRender\\古代埃及文明 封面 download.pdf";
        File file = new File(pdfPath);
        OutputStream output = new FileOutputStream(file);

        IOUtils.copy(gridFsResource.getInputStream(), output);
        output.close();
    }
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值