zoukankan      html  css  js  c++  java
  • 使用GridFsTemplate在mongodb中存取文件

    spring-data-mongodb之gridfs

     

    mongodb除了能够存储大量的数据外,还内置了一个非常好用的文件系统。
    基于mongodb集群的优势,GridFS当然也是分布式的,而且备份也方便。
    当用户把文件上传到GridFS后,文件会被分割成大小为256KB的块,并单独存放起来。

    好处如下:

    1. 可以有Replication;
    2. 可以利用MongoDB的权限访问控制;
    3. 可以利用现成的MongoDB备份方式;

    今天主要是学习如何使用data这个框架来操作GridFS

    首先配置gridFs的模板类

    <!-- Mongodb gridFs的模板 -->
     <bean id="gridFsTemplate" class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
         <constructor-arg ref="mongoDbFactory" />
         <constructor-arg ref="mappingConverter" />
     </bean>
    
    /**
      * 上传文件
      * @author yinjihuan
      * @throws Exception
      */
     public static void uploadFile() throws Exception {
         File file = new File("/Users/yinjihuan/Downlaods/logo.png");
         InputStream content = new FileInputStream(file);
         //存储文件的额外信息,比如用户ID,后面要查询某个用户的所有文件时就可以直接查询
         DBObject metadata = new BasicDBObject("userId", "1001");
         GridFSFile gridFSFile = gridFsTemplate.store(content, file.getName(), "image/png", metadata);
         String fileId = gridFSFile.getId().toString();
         System.out.println(fileId);
     }
    

    文件默认是上传到数据中的fs.files和fs.chunks中
    files是用来存储文件的信息,文件名,md5,文件大小,还有刚刚的metadata,上传时间等等数据,数据格式如下:

    {
        "_id": ObjectId("57c17bb0d4c666b6e53ba795"),
        "metadata": {
            "user_id": 1001
        },
        "filename": "file",
        "aliases": null,
        "chunkSize": NumberLong(261120),
        "uploadDate": ISODate("2016-09-08T11:38:24.999Z"),
        "length": NumberLong(165253),
        "contentType": "image/png",
        "md5": "668727a643ddd6df2e98f164d9fc90fd"
    }
    

    chunks则是用来存储文件内容的
    1.files_id就是文件的ID,也就是files集合中的_id
    2.n是文件块的索引,通常文件会被分割成256KB的块大小存储
    3.data就是文件的数据了

    当需要访问文件的时候通过文件ID可以找到文件被分成了多少块,然后从第一块按顺序开始读取,返回给用户。

    {
        "_id": ObjectId("57c18993d4c6355ffeb6f8ae"),
        "files_id": ObjectId("57c17bb0d4c666b6e53ba795"),
        "n": 0,
        "data": BinData(0,
        "iVBORw0KGgDSDDSDDSD5xNvmxT5/sHLl5oDl/Y/NtznsPTPllg9+Gqie+Yj5xNvmxT5/sHLl5oDl/Y/NtznsPTPllg9+Gqie+YjoA")
    }
    {
        "_id": ObjectId("57c18993d4c6355ffeb6f8ae"),
        "files_id": ObjectId("57c17bb0d4c666b6e53ba795"),
        "n": 1,
        "data": BinData(1,
        "iVBORw0KGgDSDDSDDSD5xNvmxT5/sHLl5oDl/Y/NtznsPTPllg9+Gqie+Yj5xNvmxT5/sHLl5oDl/Y/NtznsPTPllg9+Gqie+YjoA")
    }
    
    /**
      * 根据文件ID查询文件
      * @author yinjihuan
      * @param fileId
      * @return
      * @throws Exception
      */
     public static GridFSDBFile getFile(String fileId) throws Exception {
         return gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
     }
    
    /**
      * 根据文件ID删除文件
      * @author yinjihuan
      * @param fileId
      * @throws Exception
      */
     public static void removeFile(String fileId) throws Exception {
         gridFsTemplate.delete(Query.query(Criteria.where("_id").is(fileId)));
     }
    

    如果在Spring mvc中想直接访问存储的文件也很简单,直接通过文件ID查询该文件,然后直接输出到response就是了,记得要设置ContentType,这时就明白为什么存储的时候要把ContentType存起来了。

    /**
      * 访问图片
      * @author yinjihuan
      * @param fileId
      * @param request
      * @param response
      */
     @RequestMapping(value = "/image/{fileId}")
     @ResponseBody
     public void getImage(@PathVariable String fileId, HttpServletResponse response) {
         try {
             GridFSDBFile gridfs = filesService.getFile(fileId);
             response.setContentType(gridfs.getContentType());
             OutputStream out = response.getOutputStream();
             gridfs.writeTo(out);
             out.flush();
             out.close();
         } catch (Exception e) {
              e.printStackTrace();
         }
     }
    

    源码下载:https://github.com/yinjihuan/cxytiandi

    Store Retrive and Query Image File Using Mongodb GridFs And Spring Data

      

    In previous tutorials, we learned about How to Install Mongodb On Windows platform and Implement CRUD Operations Using MongoDB And Spring Data. This tutorial will help to store,retrieve image file using Mongodb GridFs specification.

     

    Tools and Technologies

    Basically we are using below maven dependencies

    1. Maven 3.0.4
    2. JDK 1.6
    3. Spring Core 4.0.3.RELEASE
    4. Spring Data Mongodb 1.5.2.RELEASE

    Maven Dependencies

    We need to define required dependencies and their versions in pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>
     <groupId>org.springframework.data.examples</groupId>
     <artifactId>spring-data-examples</artifactId>
     <version>0.0.1-SNAPSHOT</version>
     <name>SpringMongoExamples</name>
     <dependencies>
      <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-core</artifactId>
       <version>4.0.3.RELEASE</version>
      </dependency>
      <dependency>
       <groupId>org.springframework.data</groupId>
       <artifactId>spring-data-mongodb</artifactId>
       <version>1.5.2.RELEASE</version>
      </dependency>
    
     </dependencies>
     <build>
      <finalName>SpringMongoExamples</finalName>
      <plugins>
       <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
         <source>1.6</source>
         <target>1.6</target>
        </configuration>
       </plugin>
      </plugins>
     </build>
    </project>

    org.springframework I am using spring 4.0.3.RELEASE version. we required only spring-core artifact of Spring Framework because this is stand-alone java application

    org.springframework.data Spring Data for MongoDB is part of the parent Spring Data project. You can define the respected dependency in pom.xml

    Once you define your maven dependencies in pom.xml, please execute the maven command mvn clean install -e so that it will start downloading the respected jars files

    spring data mongo db crud eclipse project setup

    FileStorageDao Interface

    Here we are going to use DAO pattern to perform Db operation with MongoDb, Which store and retrive the image File. So lets define below methods in FileStorageDao interface.

    package com.technicalkeeda.dao;
    
    import java.io.InputStream;
    import java.util.List;
    
    import com.mongodb.DBObject;
    import com.mongodb.gridfs.GridFSDBFile;
    
    public interface FileStorageDao {
    
     public String store(InputStream inputStream, String fileName,
       String contentType, DBObject metaData);
     
     public GridFSDBFile retrive(String fileName);
    
     public GridFSDBFile getById(String id);
    
     public GridFSDBFile getByFilename(String filename);
    
     public List findAll();
    
    }

    FileStorageDao Implementation

    This is MongoDB specific implementation to perform different Image operations using GridFsTemplate similar to MongoTemplate. Its not specific to Image file you can store or save any type of files like .doc, .xls and.pdf etc.

    The template can now be injected and used to perform storage and retrieval operations.The store operations take an InputStream, a filename and optionally metadata information about the file to store. The metadata can be an arbitrary object which will be marshalled by the MongoConverter configured with the GridFsTemplate

    package com.technicalkeeda.dao;
    
    import java.io.InputStream;
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.mongodb.core.query.Criteria;
    import org.springframework.data.mongodb.core.query.Query;
    import org.springframework.data.mongodb.gridfs.GridFsTemplate;
    
    import com.mongodb.DBObject;
    import com.mongodb.gridfs.GridFSDBFile;
    
    public class FileStorageDaoImpl implements FileStorageDao {
    
     @Autowired
     GridFsTemplate gridFsTemplate;
    
     public String store(InputStream inputStream, String fileName,
       String contentType, DBObject metaData) {
      return this.gridFsTemplate
        .store(inputStream, fileName, contentType, metaData).getId()
        .toString();
     }
    
     public GridFSDBFile getById(String id) {
      return this.gridFsTemplate.findOne(new Query(Criteria.where("_id").is(
        id)));
     }
    
     public GridFSDBFile getByFilename(String fileName) {
      return gridFsTemplate.findOne(new Query(Criteria.where("filename").is(
        fileName)));
     }
    
     public GridFSDBFile retrive(String fileName) {
      return gridFsTemplate.findOne(
        new Query(Criteria.where("filename").is(fileName)));
     }
    
     public List findAll() {
      return gridFsTemplate.find(null);
     }
    
    }

    Spring MongoDB Bean Configuration

    Lets define the required bean dependencies using spring configuration file. spring-beans.xml file is located under folder /src/main/resources/spring-beans.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
     xmlns:mongo="http://www.springframework.org/schema/data/mongo"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
            http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd">
     <context:annotation-config />
    
     <context:component-scan base-package="com.technicalkeeda">
      <context:exclude-filter type="annotation"
       expression="org.springframework.context.annotation.Configuration" />
     </context:component-scan>
     
     <!-- Connection to MongoDB server -->
     <mongo:db-factory host="localhost" port="27017" dbname="griddemo" />
     <mongo:mapping-converter id="converter" db-factory-ref="mongoDbFactory" />
     
     <!-- Define MongoDB GridFS Template -->
     <bean id="gridTemplate" class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
      <constructor-arg ref="mongoDbFactory" />
      <constructor-arg ref="converter" />
     </bean>
    
     <bean id="fileStorageDao" class="com.technicalkeeda.dao.FileStorageDaoImpl"></bean>
    
    </beans>

    <mvc:annotation-driven /> declares explicit support for annotation-driven code (i.e. @Document, @Id and @Autowired)

    Here I am using the <context:component-scan.... tag to which have to scan my files and searching the annotations.

    Register a MongoDbFactory instance using XML metadata

     <mongo:db-factory id="mongoDbFactory" host="localhost" port="27017" dbname="griddemo" />
    
    <bean id="gridTemplate" class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
      <constructor-arg ref="mongoDbFactory" />
      <constructor-arg ref="converter" />
     </bean>

    In the above configuration creates mongo instance using the default host, port number and dbname(localhost , 27017 and griddemo). The SimpleMongoDbFactory registered with the container is identified by the id 'mongoDbFactory' unless a value for the id attribute is specified

    The GridFsTemplate MongoDB supports storing binary files inside itâ??s filesystem GridFS. Spring Data MongoDB provides a GridFsOperations interface as well as the according implementation GridFsTemplate to easily interact with the filesystem. You can setup a GridFsTemplate instance by handing it a MongoDbFactory as well as a MongoConverter

    Spring Data MongoDB Test Class

    App.java is the test class which runs the CRUD operation on MongoDB database. Execute the App.java and verify the output.

    package com.technicalkeeda.app;
    
    import java.io.IOException;
    import java.io.InputStream;
    
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.core.io.Resource;
    
    import com.mongodb.BasicDBObject;
    import com.mongodb.DBObject;
    import com.mongodb.gridfs.GridFSDBFile;
    import com.technicalkeeda.dao.FileStorageDao;
    
    public class App {
     public static void main(String[] args) {
      InputStream inputStream = null;
      try {
       ApplicationContext context = new ClassPathXmlApplicationContext(
         "spring-beans.xml");
       FileStorageDao fileStorageDao = (FileStorageDao) context
         .getBean("fileStorageDao");
       Resource resource = context.getResource("file:c:\audi.jpg");
    
       DBObject metaData = new BasicDBObject();
       metaData.put("brand", "Audi");
       metaData.put("model", "Audi A3");
       metaData.put("description","Audi german automobile manufacturer that designs, engineers, and distributes automobiles");
    
       String id = fileStorageDao.store(resource.getInputStream(),"audi.jpg", "image/jpeg", metaData);
    
       System.out.println("Find By Id----------------------");
       GridFSDBFile byId = fileStorageDao.getById(id);
       System.out.println("File Name:- " + byId.getFilename());
       System.out.println("Content Type:- " + byId.getContentType());
       
       
       
       System.out.println("Find By Filename----------------------");
       GridFSDBFile byFileName = fileStorageDao.getByFilename("audi.jpg");
       System.out.println("File Name:- " + byFileName.getFilename());
       System.out.println("Content Type:- " + byFileName.getContentType());
       
       
       System.out.println("List All Files----------------------");
       for (GridFSDBFile file : fileStorageDao.findAll()) {
        System.out.println("File Name:- " + file.getFilename());
        System.out.println("Content Type:- " + file.getContentType());
        System.out.println("Meta Data Brand:- " + file.getMetaData().get("brand"));
        System.out.println("Meta Data Model:- " + file.getMetaData().get("model"));
        System.out.println("Meta Data Description:- " + file.getMetaData().get("description"));
       }
       
       GridFSDBFile retrive = fileStorageDao.retrive("audi.jpg");
       retrive.writeTo("c:\newaudi.jpg");
       
      } catch (BeansException e) {
       System.out.println("BeansException:-" + e.getMessage());
      } catch (IOException e) {
       System.out.println("IOException:-" + e.getMessage());
      } finally {
       if (inputStream != null) {try{
         inputStream.close();}catch(IOException e){System.out.println("IOException Finally:-"+ e.getMessage());}}}}}

     

     

    I just announced the new Spring 5 modules in REST With Spring:

    >> CHECK OUT THE COURSE

    1. Overview

    This tutorial will explore one of the core features of Spring Data MongoDB: interacting with GridFS.

    The GridFS storage spec is mainly used for working with files that exceed the BSON-document size limit of 16MB. And Spring Data provides a GridFsOperations interface and its implementation – GridFsTemplate – to easily interact with this filesystem.

    2. Configuration

    2.1. XML Configuration

    Let’s start with the simple XML configuration for the GridFsTemplate:

    1
    2
    3
    4
    <bean id="gridFsTemplate" class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
        <constructor-arg ref="mongoDbFactory" />
        <constructor-arg ref="mongoConverter" />
    </bean>

    The constructor arguments to the GridFsTemplate include bean references to mongoDbFactory, which creates a Mongo database, and mongoConverter, which converts between Java and MongoDB types. Their bean definitions are below.

    1
    2
    3
    4
    5
    <mongo:db-factory id="mongoDbFactory" dbname="test" mongo-ref="mongo" />
     
    <mongo:mapping-converter id="mongoConverter" base-package="org.baeldung.converter">
        <mongo:custom-converters base-package="org.baeldung.converter"/>
    </mongo:mapping-converter>

    2.2. Java Configuration

    Let’s create a similar configuration, only with Java:

    1
    2
    3
    4
    @Bean
    public GridFsTemplate gridFsTemplate() throws Exception {
        return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
    }

    For this configuration we used mongoDbFactory and mappingMongoConverter from org.springframework.data.mongodb.config.AbstractMongoConfiguration.

    3. GridFsTemplate Core Methods

    3.1. store

    The store method saves a file into MongoDB.

    Suppose we have an empty database and wish to store a file in it:

    1
    2
    3
    InputStream inputStream = new FileInputStream("src/main/resources/test.png");
    String id =
      gridFsTemplate.store(inputStream, "test.png", "image/png", metaData).getId().toString();

    Note that we can save additional metadata along with the file by passing a DBObject to the store method. For our example, the DBObject might look something like this:

    1
    2
    DBObject metaData = new BasicDBObject();
    metaData.put("user", "alex");

    GridFS uses two collections to store the file metadata and its content. The file’s metadata is stored in the files collection, and the file’s content is stored in the chunks collection. Both collections are prefixed with fs.

    If we execute the MongoDB command db[‘fs.files’].find(), we will see the fs.files collection:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    {
        "_id" : ObjectId("5602de6e5d8bba0d6f2e45e4"),
        "metadata" : {
            "user" : "alex"
        },
        "filename" : "test.png",
        "aliases" : null,
        "chunkSize" : NumberLong(261120),
        "uploadDate" : ISODate("2015-09-23T17:16:30.781Z"),
        "length" : NumberLong(855),
        "contentType" : "image/png",
        "md5" : "27c915db9aa031f1b27bb05021b695c6"
    }

    The command db[‘fs.chunks’].find() retrieves the file’s content:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    {
        "_id" : ObjectId("5602de6e5d8bba0d6f2e45e4"),
        "files_id" : ObjectId("5602de6e5d8bba0d6f2e45e4"),
        "n" : 0,
        "data" :
        {
            "$binary" : "/9j/4AAQSkZJRgABAQAAAQABAAD/4QAqRXhpZgAASUkqAAgAAAABADEBAgAHAAAAGgAAAAAAAABHb29nbGUAAP/bAIQAAwICAwICAwMDAwQDAwQFCAUFBAQFCgcHBggM
              CgwMCwoLCw0OEhANDhEOCwsQFhARExQVFRUMDxcYFhQYEhQVFAEDBAQGBQUJBgYKDw4MDhQUFA8RDQwMEA0QDA8VDA0NDw0MDw4MDA0ODxAMDQ0MDAwODA8MDQ4NDA0NDAwNDAwQ/8AA
              EQgAHAAcAwERAAIRAQMRAf/EABgAAQEBAQEAAAAAAAAAAAAAAAgGBwUE/8QALBAAAgEDAgQFAwUAAAAAAAAAAQIDBAURBiEABwgSIjFBYXEyUYETFEKhw
              f/EABoBAAIDAQEAAAAAAAAAAAAAAAMEAQIFBgD/xAAiEQACAgEDBAMAAAAAAAAAAAAAAQIRAyIx8BJRYYETIUH/2gAMAwEAAhEDEQA/AHDyq1Bb6GjFPMAszLkZHHCTi1I6O
              cXOFRZ1ZqoX6aqzRClkhb9MGVh2SsNyVI/hjG5389tuGcUaLK1GmFfpn5r3rnXpfV82pGtS3a0XmaGOO3zguKV1SWDwBQDH2uUWTOWMZzuM8bS0VQtJKRb2li9LL3l+4VNQPEfQTOB/WO
              G1K0JtUzwad1eZaYBiqzL4S2N8cZUsa7DqlRGdWvMq5aX6b9Tvb5pIZbggt7VcU3YacSkDbfuLNuu3lkk+98GNfIrLt2gK9K/NWl5Z87Ldebj3R0NTa2tVVKhOI0KoQ5AG4DRqSPk+gHGn
              khUPYNOx92vW9PcrdDW0FUJqOp7po5ETIYMxOdyOAK0qAvcgKPWa0oMTo7SEYDKPp98/5wPoJsx3rZ1wLhojS9iinLD9w9W47iSwVe0Z3wfrPoce2eC4I6rCX9MxrpUpWqudNunUosNLR1EkiyIGDqUKF
              fyZB+AeG80riueQdVfObC/tN1pLdaLfSxMiRQ08aIg2CjtGAB9uEyCSqSWujICUXwghT57A5+ePEoMvUdc5a3XlSsgUhZGjGM/TGAqjz+SfuT7DDmGC6WzzeyOv0+2amOrr3KylzTUwjjDeWGbJJ9/COI
              yvRFFv1iRsVGDaqYGWVsIoBZydsDhQGf/Z",
            "$type" : "00"
        }
    }

    3.2. findOne

    findOne returns exactly one document that satisfies the specified query criteria.

    1
    2
    String id = "5602de6e5d8bba0d6f2e45e4";
    GridFSDBFile gridFsdbFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id)));

    The code above will return the result record which was added in the example above. If the database contained more than one record which matched the query, it would return only one document. The specific record returned would be selected according to natural ordering (the order in which the documents were stored in the database).

    3.3. find

    find selects documents from a collection and returns a cursor to the selected documents.

    Suppose we have the following database, containing 2 records:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    [
        {
            "_id" : ObjectId("5602de6e5d8bba0d6f2e45e4"),
            "metadata" : {
                "user" : "alex"
            },
            "filename" : "test.png",
            "aliases" : null,
            "chunkSize" : NumberLong(261120),
            "uploadDate" : ISODate("2015-09-23T17:16:30.781Z"),
            "length" : NumberLong(855),
            "contentType" : "image/png",
            "md5" : "27c915db9aa031f1b27bb05021b695c6"
        },
        {
            "_id" : ObjectId("5702deyu6d8bba0d6f2e45e4"),
            "metadata" : {
                "user" : "david"
            },
            "filename" : "test.png",
            "aliases" : null,
            "chunkSize" : NumberLong(261120),
            "uploadDate" : ISODate("2015-09-23T17:16:30.781Z"),
            "length" : NumberLong(855),
            "contentType" : "image/png",
            "md5" : "27c915db9aa031f1b27bb05021b695c6"
        }
    ]

    If we use the GridFsTemplate to execute the following query:

    1
    List<GridFSDBFile> gridFSDBFiles = gridFsTemplate.find(null);

    The resulting list should contain two records, since we provided no criteria.

    We can, of course, provide some criteria to the find method. For example, if we would like to get files whose metadata contains users with name alex, the code would be:

    1
    2
    List<GridFSDBFile> gridFsdbFiles =
      gridFsTemplate.find(new Query(Criteria.where("metadata.user").is("alex")));

    The resulting list will contain only one record.

    3.4. delete

    delete removes documents from a collection.

    Using the database from the previous example, suppose we have the code:

    1
    2
    String id = "5702deyu6d8bba0d6f2e45e4";
    gridFsTemplate.delete(new Query(Criteria.where("_id").is(id)));

    After executing delete, only one record remains in the database:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    {
        "_id" : ObjectId("5702deyu6d8bba0d6f2e45e4"),
        "metadata" : {
            "user" : "alex"
        },
        "filename" : "test.png",
        "aliases" : null,
        "chunkSize" : NumberLong(261120),
        "uploadDate" : ISODate("2015-09-23T17:16:30.781Z"),
        "length" : NumberLong(855),
        "contentType" : "image/png",
        "md5" : "27c915db9aa031f1b27bb05021b695c6"
    }

    with chunks:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    {
        "_id" : ObjectId("5702deyu6d8bba0d6f2e45e4"),
        "files_id" : ObjectId("5702deyu6d8bba0d6f2e45e4"),
        "n" : 0,
        "data" :
        {
            "$binary" : "/9j/4AAQSkZJRgABAQAAAQABAAD/4QAqRXhpZgAASUkqAAgAAAABADEBAgAHAAAAGgAAAAAAAABHb29nbGUAAP/bAIQAAwICAwICAwMDAwQDAwQFCAUFBAQFCgcHBggM
              CgwMCwoLCw0OEhANDhEOCwsQFhARExQVFRUMDxcYFhQYEhQVFAEDBAQGBQUJBgYKDw4MDhQUFA8RDQwMEA0QDA8VDA0NDw0MDw4MDA0ODxAMDQ0MDAwODA8MDQ4NDA0NDAwNDAwQ/8AA
              EQgAHAAcAwERAAIRAQMRAf/EABgAAQEBAQEAAAAAAAAAAAAAAAgGBwUE/8QALBAAAgEDAgQFAwUAAAAAAAAAAQIDBAURBiEABwgSIjFBYXEyUYETFEKhw
              f/EABoBAAIDAQEAAAAAAAAAAAAAAAMEAQIFBgD/xAAiEQACAgEDBAMAAAAAAAAAAAAAAQIRAyIx8BJRYYETIUH/2gAMAwEAAhEDEQA/AHDyq1Bb6GjFPMAszLkZHHCTi1I6O
              cXOFRZ1ZqoX6aqzRClkhb9MGVh2SsNyVI/hjG5389tuGcUaLK1GmFfpn5r3rnXpfV82pGtS3a0XmaGOO3zguKV1SWDwBQDH2uUWTOWMZzuM8bS0VQtJKRb2li9LL3l+4VNQPEfQTOB/WO
              G1K0JtUzwad1eZaYBiqzL4S2N8cZUsa7DqlRGdWvMq5aX6b9Tvb5pIZbggt7VcU3YacSkDbfuLNuu3lkk+98GNfIrLt2gK9K/NWl5Z87Ldebj3R0NTa2tVVKhOI0KoQ5AG4DRqSPk+gHGn
              khUPYNOx92vW9PcrdDW0FUJqOp7po5ETIYMxOdyOAK0qAvcgKPWa0oMTo7SEYDKPp98/5wPoJsx3rZ1wLhojS9iinLD9w9W47iSwVe0Z3wfrPoce2eC4I6rCX9MxrpUpWqudNunUosNLR1EkiyIGDqUKF
              fyZB+AeG80riueQdVfObC/tN1pLdaLfSxMiRQ08aIg2CjtGAB9uEyCSqSWujICUXwghT57A5+ePEoMvUdc5a3XlSsgUhZGjGM/TGAqjz+SfuT7DDmGC6WzzeyOv0+2amOrr3KylzTUwjjDeWGbJJ9/COI
              yvRFFv1iRsVGDaqYGWVsIoBZydsDhQGf/Z",
            "$type" : "00"
        }
    }

    3.5. getResources

    getResources returns all GridFsResource with the given file name pattern.

    Suppose we have the following records in the database:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    [
       {
           "_id" : ObjectId("5602de6e5d8bba0d6f2e45e4"),
           "metadata" : {
               "user" : "alex"
           },
           "filename" : "test.png",
           "aliases" : null,
           "chunkSize" : NumberLong(261120),
           "uploadDate" : ISODate("2015-09-23T17:16:30.781Z"),
           "length" : NumberLong(855),
           "contentType" : "image/png",
           "md5" : "27c915db9aa031f1b27bb05021b695c6"
       },
       {
           "_id" : ObjectId("5505de6e5d8bba0d6f8e4574"),
           "metadata" : {
               "user" : "david"
           },
           "filename" : "test.png",
           "aliases" : null,
           "chunkSize" : NumberLong(261120),
           "uploadDate" : ISODate("2015-09-23T17:16:30.781Z"),
           "length" : NumberLong(855),
           "contentType" : "image/png",
           "md5" : "27c915db9aa031f1b27bb05021b695c6"
        },
        {
           "_id" : ObjectId("5777de6e5d8bba0d6f8e4574"),
           "metadata" : {
               "user" : "eugen"
           },
           "filename" : "baeldung.png",
           "aliases" : null,
           "chunkSize" : NumberLong(261120),
           "uploadDate" : ISODate("2015-09-23T17:16:30.781Z"),
           "length" : NumberLong(855),
           "contentType" : "image/png",
           "md5" : "27c915db9aa031f1b27bb05021b695c6"
        }
    1
    ]

    Now let’s execute getResources using a file pattern:

    1
    GridFsResource[] gridFsResource = gridFsTemplate.getResources("test*");

    This will return the two records whose file names begin with “test” (in this case, they are both named test.png).

    4. GridFSDBFile Core Methods

    The GridFSDBFile API is quite simple as well:

    • getInputStream – returns an InputStream from which data can be read
    • getFilename – gets the filename of the file
    • getMetaData – gets the metadata for the given file
    • containsField – determines if the document contains a field with the given name
    • get – gets a field from the object by name
    • getId – gets the file’s object ID
    • keySet – gets the object’s field names

    5. Conclusion

    In this article we looked at the GridFS features of MongoDB, and how to interact with them using Spring Data MongoDB.

    The implementation of all these examples and code snippets can be found in my github project – this is an Eclipse based project, so it should be easy to import and run as it is.

     
  • 相关阅读:
    如何:使用向导来处理项目模板 【转载】
    .NET : 如何在生成XML文档时绑定样式表
    如何在生产环境部署K2的流程
    SQL Server 数据库文档生成工具开源项目【合作邀请】
    新的纪元
    SharePoint : 谁说WSS不支持审核
    C++ : 类型的别名和对象的别名
    C++: 引用和地址运算符
    Infopath : 如何通过代码复制格式文本框的值
    正确地使用投影仪和移动硬盘
  • 原文地址:https://www.cnblogs.com/pejsidney/p/9076107.html
Copyright © 2011-2022 走看看