zoukankan      html  css  js  c++  java
  • MongoDb学习(五)--Gridfs--上传下载

    版本

          <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>2.1.3.RELEASE</version>
      </dependency>

    使用的时候注意版本,2.x以上某些方法进行了更改。gridfs下载在2.x以下版本为

        private static void download() {
            GridFSDBFile fs = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is("58da69a45aa6c70234eb70f1")));
            try {
                fs.writeTo("/home/a.txt");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    2.x以上版本。find的返回值进行了更改。需要使用如下方法进行下载

    find找到fs后,调用

    getResource方法。然后进行java的文件存储。
    
    
    private static void download() {
            GridFSFile fs = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is("5c0619774a24a3408284b4b3")));
            GridFsResource gs = gridFsTemplate.getResource(fs);
            OutputStream os = null;
            try {
                byte[] bs = new byte[1024];
                int len;
                InputStream in = gs.getInputStream();
                File file = new File("/home/chaoba/");
                os = new FileOutputStream(file.getPath() + File.separator + gs.getFilename());
                while ((len = in.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }

    上传方法

        private static void upload() {
    
            File file = new File("/home/chaoba/Downloads/抖音-日版.apk");
            try {
                ObjectId id = gridFsTemplate.store(new FileInputStream(file), file.getName(),
                        new Document().put("user", "admin"));
                System.out.println(id);
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
    
        }
    一万年太久,只争朝夕!
  • 相关阅读:
    P3704 [SDOI2017]数字表格
    CF 700 E. Cool Slogans
    杜教筛学习笔记
    [BOI2004]Sequence 数字序列(左偏树)
    [WC2007]剪刀石头布(最大流)
    [NOI2009]变换序列(二分图匹配)
    文理分科(最小割)
    上帝与集合的正确用法(欧拉定理)
    [HAOI2008]圆上的整点(数论)
    主席树学习笔记
  • 原文地址:https://www.cnblogs.com/chaoba/p/10063961.html
Copyright © 2011-2022 走看看