-
GridFS介紹
GridFS是MongoDB提供的用于持久化存儲檔案的子產品,CMS使用MongoDB存儲資料,使用GridFS可以快速內建開發。
它的工作原理是:
在GridFS存儲檔案是将檔案分塊存儲,檔案會按照256KB的大小分割成多個塊進行存儲,GridFS使用兩個集合(collection)存儲檔案,一個集合是chunks, 用于存儲檔案的二進制資料;一個集合是files,用于存儲檔案的中繼資料資訊(檔案名稱、塊大小、上傳時間等資訊)。
從GridFS中讀取檔案要對檔案的各各塊進行組裝、合并。
詳細參考:https://docs.mongodb.com/manual/core/gridfs/
@Test
public void testGridFs() throws FileNotFoundException {
//要存儲的檔案
File file = new File("d:/a.html");
//定義輸入流
FileInputStream inputStram = new FileInputStream(file);
//向GridFS存儲檔案
ObjectId objectId = = gridFsTemplate.store(inputStram, "測試檔案01", "");
//得到檔案ID
String fileId = objectId.toString();
System.out.println(file);
}
@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;
}
}
@SpringBootTest
@RunWith(SpringRunner.class)
public class GridFsTest {
@Autowired
GridFsTemplate gridFsTemplate;
@Autowired
GridFSBucket gridFSBucket;
@Test
public void queryFile() throws IOException {
String fileId = "5b9c54e264c614237c273621";
//根據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);
}
}
@Test
public void testDelFile() throws IOException {
//根據檔案id删除fs.files和fs.chunks中的記錄
gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5b9c54e264c614237c273621")));
}