一、介绍
GridFS是MongoDB提供的用于持久化存储文件的模块,CMS使用MongoDB存储数据,使用GridFS可以快速集成 开发。 它的工作原理是: 在GridFS存储文件是将文件分块存储,文件会按照256KB的大小分割成多个块进行存储,GridFS使用两个集合 (collection)存储文件,一个集合是chunks, 用于存储文件的二进制数据;一个集合是files,用于存储文件的元数 据信息(文件名称、块大小、上传时间等信息)。 从GridFS中读取文件要对文件的各各块进行组装、合并。
详细参考:https://docs.mongodb.com/manual/core/gridfs/
二、实例
1、GridFS存取文件测试
1、存文件
使用GridFsTemplate存储文件测试代码:
向测试程序注入GridFsTemplate。
@SpringBootTest
@RunWith(SpringRunner.class)
public class GridFsTest {
@Autowired
GridFsTemplate gridFsTemplate;
/**
* 存文件
*/
@Test
public void testGridFsSaveFile() throws FileNotFoundException {
//要存储的文件
File file = new File("e:/index_banner.ftl");
// 定义输入流
FileInputStream inputStram = new FileInputStream(file);
// 向GridFS存储文件
ObjectId objectId = gridFsTemplate.store(inputStram, "轮播图测试文件01", "");
// 得到文件ID
String fileId = objectId.toString();
System.out.println(file);
}
}
存储原理说明:
文件存储成功得到一个文件id
此文件id是fs.files集合中的主键。
可以通过文件id查询fs.chunks表中的记录,得到文件的内容。
2、读取文件
1)在config包中定义Mongodb的配置类,
如下: GridFSBucket用于打开下载流对象
/**
* @author 麦客子
* @desc Mongodb的配置类
* @email leeshuhua@163.com
* @create 2019/07/17 21:53
**/
@Configuration
public class MongoConfig {
@Value("${spring.data.mongodb.database}")
String db;
/**
* GridFSBucket用于打开下载流对象
* @param mongoClient
* @return
*/
@Bean
public GridFSBucket getGridFSBucket(MongoClient mongoClient) {
MongoDatabase database = mongoClient.getDatabase(db);
GridFSBucket bucket = GridFSBuckets.create(database);
return bucket;
}
}
测试代码:
@SpringBootTest
@RunWith(SpringRunner.class)
public class GridFsTest {
@Autowired
GridFsTemplate gridFsTemplate;
@Autowired
GridFSBucket gridFSBucket;
/**
* 读取文件
* @throws IOException
*/
@Test
public void queryFile() throws IOException {
String fileId = "5d2f261dd8d5cf41c0465db3";
// 根据id查询文件
GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
// 打开下载流对象
GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
// 创建gridFsResource,用于获取流对象
GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
// 获取流中的数据
String s = IOUtils.toString(gridFsResource.getInputStream(), "utf-8");
System.out.println(s);
}
}
3、删除文件
/**
* 删除文件
* @throws IOException
*/
@Test
public void testDelFile() throws IOException {
//根据文件id删除fs.files和fs.chunks中的记录
gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5d2f261dd8d5cf41c0465db3")));
}