GridFS是MongoDB提供的用於持久化存儲文件的模塊,CMS使用MongoDB存儲數據,使用GridFS能夠快速集成開發。
它的工做原理是:
在GridFS存儲文件是將文件分塊存儲,文件會按照256KB的大小分割成多個塊進行存儲,GridFS使用兩個集合(collection)存儲文件,一個集合是chunks,用於存儲文件的二進制數據;一個集合是files,用於存儲文件的元數據信息(文件名稱、塊大小、上傳時間等信息)。從GridFS中讀取文件要對文件的各各塊進行組裝、合併。java
詳細參考:https://docs.mongodb.com/manual/core/gridfs/spring
一、添加依賴mongodb
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
@Autowired GridFsTemplate gridFsTemplate; //存文件 @Test public void testStore() throws FileNotFoundException { //定義file File file =new File("D:\\a.txt"); //定義fileInputStream FileInputStream fileInputStream = new FileInputStream(file); ObjectId objectId = gridFsTemplate.store(fileInputStream, "a.txt"); //5dc6e1cf28763b92ec445496 //objectId是fs.files集合的_id字段,是fs.chunks集合的fils_id字段 System.out.println(objectId); }
配置app
@Configuration public class MongoConfig { @Value("${spring.data.mongodb.database}") String db; @Bean public GridFSBucket getGridFSBucket(MongoClient mongoClient){ MongoDatabase database = mongoClient.getDatabase(db); GridFSBucket bucket = GridFSBuckets.create(database); return bucket; } }
application.ymlspring-boot
server: port: 31001 spring: application: name: xc-service-manage-cms data: mongodb: uri: mongodb://root:123@localhost:27017 database: xc_cms
使用 server
@Autowired GridFSBucket gridFSBucket; //取文件 @Test public void queryFile() throws IOException { //根據文件id查詢文件 GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is("5dc6e1cf28763b92ec445496"))); //打開一個下載流對象 GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId()); //建立GridFsResource對象,獲取流 GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream); //從流中取數據 String content = IOUtils.toString(gridFsResource.getInputStream(), "utf-8"); System.out.println(content); }
三、刪除文件對象
@Test public void testDelFile() throws IOException { //根據文件id刪除fs.files和fs.chunks中的記錄 gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5dc6e1cf28763b92ec445496"))); }