java原生代码实现MongoDB的文件上传及下载

一、pom依赖(MongoDB驱动)

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver</artifactId>
    <version>3.4.2</version>
</dependency>

二、获取核心对象(GridFSBucket)

    private final static String URL = "127.0.0.1";
    private final static Integer PORT = 27017;
    private final static String DATABASE = "liuli";
private static MongoClient client; private static MongoDatabase db; private static GridFSBucket bucket; static{ MongoClientOptions options = MongoClientOptions.builder().build(); ServerAddress address = new ServerAddress(URL, PORT); client = new MongoClient(address, options); db = client.getDatabase(DATABASE); /*后面的名字可以自定义 * MongoDb会在数据库生成两个collections(users.chunks和users.files) * users.files存放文件信息 * users.chunks存放文件的二进制流 */ bucket = GridFSBuckets.create(db,"users"); }

三、文件上传

    /**
     * 文件上传
     */
    public void fileUp(){
        File png = new File("C:\\Users\\mayn\\Desktop\\1.png");
        GridFSUploadOptions options = null;
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(png);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Document document = new Document();
        document.put("name", "liuli");
        //metadata方法可以为文件上传的同时附加一些元数据
        options = new GridFSUploadOptions().chunkSizeBytes(358400).metadata(document);
        ObjectId id = bucket.uploadFromStream("1.png", inputStream, options);
        System.out.println("objectid="+id);
    }

四、获取文件的一些属性

    /**
     * 查询文件属性
     */
    public void fileDown(){
        bucket.find().forEach(new Block<GridFSFile>() {

            @Override
            public void apply(GridFSFile t) {
                //GridFSFile封装了所有字段
                System.out.println(t.getFilename());
            }
            
        });
    }

在MongoDB客户端我们可以看到它的内容是这样的

五、文件下载

    /**
     * 下载文件
     * @throws FileNotFoundException 
     */
    public void fileDownLoad() throws FileNotFoundException{
        bucket.downloadToStream("1.png", new FileOutputStream(new File("src\\main\\resources\\2.png")));
    }

我们可以看到文件夹中有了该文件

 

转载于:https://www.cnblogs.com/liulihaha/p/10622261.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值