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);
}