GridFS介绍
GridFS是MongoDB提供的用于持久化存储文件的模块,CMS使用MongoDB存储数据,使用GridFS可以快速集成开发。
//缺点是效率没有那么高效..
工作原理的话我在百度找了一张图,
// 详细的话可以参考 https://docs.mongodb.com/manual/core/gridfs/
gridfs使用 - . -
存储文件
@Resource
GridFsTemplate gridFsTemplate;
@Test
public void test2() throws FileNotFoundException {
File file = new File("D:\\Code\\xuecheng\\XcEduCode\\testfreemark\\src\\main\\resources\\templates\\index_banner.ftl");
//创建输入流
FileInputStream inputStream = new FileInputStream(file);
//向 gridtemplate 存储文件
ObjectId objId = gridFsTemplate.store(inputStream, "轮播图测试文件", "");
//id 转换成字符串格式
String id = objId.toString();
System.out.println(id);
// 5bfb661d4402c333342a9c6a
// gridFsTemplate.store(, );
}
查询文件
1. 需要配置一个bean,这个bean的作用是打开下载流文件
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@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;
}
}
@Resource
GridFSBucket gridFSBucket;
//模板查询
@Test
public void fun02() throws IOException {
String id = "5bfbad494402c33ad0b6dc05";
GridFSFile fsFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)));
//打开下载流文件
GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(fsFile.getObjectId());
//创建gridFsResource,用于获取流对象
GridFsResource gridFsResource = new GridFsResource(fsFile, gridFSDownloadStream);
//获取流中的数据
String s = IOUtils.toString(gridFsResource.getInputStream(), "UTF‐8");
System.out.println(s);
}