工作原理是: GridFS存储文件是将文件分块存储,文件会按照256kb的大小分割成多个快进行存储,集合chunks用于存储文件的二进制数据,集合files用于存储文件的数据消息
向GridFS中存储文件代码:
@Autowired GridFsTemplate gridFsTemplate; public void testStore() throws FileNotFoundException { //定义file File file =new File("d:/course.ftl"); //定义fileInputStream FileInputStream fileInputStream = new FileInputStream(file); //返回的是存储在MongoDB的文件id ObjectId objectId = gridFsTemplate.store(fileInputStream, "course.ftl"); System.out.println(objectId); }此文件id是fs.files集合中的主键。可以通过文件id查询fs.chunks表中的记录,得到文件的内容。 从GridFS中下载文件代码: 1在config包中定义Mongodb的配置类:GridFSBucket用于打开下载流对象
@Configuration public class MongoConfig { //MongoDB配置文件读取操作的database名字 @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; } } @Configuration public class MongoConfig { @Autowired GridFsTemplate gridFsTemplate; @Autowired GridFSBucket gridFSBucket; @Test public void queryFile() throws IOException { //根据文件id查询文件 GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is("5f771b9eba03c57174f1775d"))); //打开一个下载流对象 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); } }