GridFS介绍
GridFS是MongoDB提供的用于持久化存储文件的模块,CMS使用MongoDB存储数据,使用GridFS可以快速集成开发。
工作原理:
在GridFS存储文件是将文件分块存储,文件会按照256KB的大小分割成多个块进行存储,GridFS使用两个集合(collection)存储文件,一个集合是chunks,用于存储文件的二进制数据;一个集合是files,用于存储文件的元数据信息(文件名称、块大小、上传时间等信息)。
从GridFS中读取文件要对文件的各个块进行组装、合并。
1、存文件
测试代码如下
1 @Test 2 public void testGridFs() throws FileNotFoundException { 3 //要存储的文件 4 File file = new File("d:/index_banner.html"); 5 //定义输入流 6 FileInputStream inputStram = new FileInputStream(file); 7 //向GridFS存储文件 8 ObjectId objectId = = gridFsTemplate.store(inputStram, "轮播图测试文件01", ""); 9 //得到文件ID 10 String fileId = objectId.toString(); 11 //输出文件 12 System.out.println(file); 13 }
存储原理说明:
文件存储成功得到一个文件id
此文件id是fs.files集合中的主键。
可以通过文件id查询fs.chunks表中的记录,得到文件的内容。
2、读取文件
1)在config包中定义Mongodb的配置类,如下:
GridFSBucket用于打开下载流对象
1 @Configuration 2 public class MongoConfig { 3 ? 4 @Value("${spring.data.mongodb.database}") 5 String db; 6 ? 7 @Bean 8 public GridFSBucket getGridFSBucket(MongoClient mongoClient){ 9 MongoDatabase database = mongoClient.getDatabase(db); 10 GridFSBucket bucket = GridFSBuckets.create(database); 11 return bucket; 12 } 13 } 14 ?
${spring.data.mongodb.database}:用于指定配置文件中的数据库
1 #在springboot的application.yml的配置文件中配置 2 3 spring: 4 data: 5 mongodb: 6 uri: mongodb://localhost:27017 7 database: xc_cms
2)测试代码如下
1 @SpringBootTest 2 @RunWith(SpringRunner.class) 3 public class GridFsTest { 4 ? 5 @Autowired 6 GridFsTemplate gridFsTemplate; 7 ? 8 @Autowired 9 GridFSBucket gridFSBucket; 10 11 @Test 12 public void queryFile() throws IOException { 13 //获取id 14 String fileId = "5b9c54e264c614237c271a99"; 15 //根据id查询文件(_id数据库中fileId对应的键值) 16 GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId))); 17 //打开下载流对象 18 GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId()); 19 //创建gridFsResource,用于获取流对象 20 GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream); 21 //获取流中的数据 22 String s = IOUtils.toString(gridFsResource.getInputStream(), "UTF-8"); 23 System.out.println(s); 24 } 25 ...
3、删除文件
1 //删除文件 2 @Test 3 public void testDelFile() throws IOException { 4 //根据文件id删除fs.files和fs.chunks中的记录 5 gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5b32480ed3a022164c4d2f92"))); 6 }
原文:https://www.cnblogs.com/foshuo-cv/p/11953026.html