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();
        }

    }
一万年太久,只争朝夕!
原文地址:https://www.cnblogs.com/chaoba/p/10063961.html