本篇内容介绍了“GridFS的原理和应用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
GridFS是MongoDB提供的用于持久化存储文件的模块,CMS使用Mongo DB存储数据,使用FGridFS可以快速集成开发。
工作原理:
在GridFS存储文件是将文件分块存储,文件会按照256KB的大小分割成多个块进行存储,GridFS使用两个集合(collection)存储文件,一个集合是chunks,用于存储文件的二进制数据;一个集合是files,用于存储文件的元数据(文件名称,大小,上传时间等信息)。
入门代码:
一、添加依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency>
二、创建启动类
package lianbang.wu.gridfs; import com.mongodb.MongoClient; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @SpringBootApplication public class GridFSApplication { public static void mainString[] args) { SpringApplication.runGridFSApplication.class); } }
三、配置文件
server: port: 31001 spring: application: name: xc-service-manage-cms data: mongodb: uri: mongodb://root:123@localhost:27017 #mongodb连接 database: xc-cms #数据库名称
四、创建配置类
@Configuration public class GridFsConfig { @Value"${spring.data.mongodb.database}") String db; @Bean public GridFSBucket getGridFSBucketMongoClient mongoClient){ MongoDatabase database = mongoClient.getDatabasedb); GridFSBucket bucket = GridFSBuckets.createdatabase); return bucket; } }
五、测试代码
public class GridFSTest { @Autowired GridFsTemplate gridFsTemplate; @Autowired GridFSBucket gridFSBucket; //保存文件 @Test public void testGridFs) throws FileNotFoundException { File file = new File"d:/index_banner.html"); FileInputStream fileInputStream = new FileInputStreamfile); ObjectId objectId = gridFsTemplate.storefileInputStream, "测试文件"); String fileId = objectId.toString); System.out.printlnfileId); } //读取文件 @Test public void queryFile) throws IOException { String fileId = "123456";//模拟的id GridFSFile gridFSFile = gridFsTemplate.findOneQuery.queryCriteria.where"_id").isfileId))); GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStreamgridFSFile.getObjectId)); GridFsResource gridFsResource = new GridFsResourcegridFSFile,gridFSDownloadStream); String string = IOUtils.toStringgridFsResource.getInputStream), "utf-8"); System.out.printlnstring); } //删除文件 @Test public void testDelFile){ gridFsTemplate.deleteQuery.queryCriteria.where"_id").is"1234"))); } }