GridFS是MongoDB提供的用於持久化存儲文件的模塊
工作原理:
GridFS將文件分塊存儲,文件會按照256KB的大小分割成多個塊進行存儲。GridFS存儲文件用到了兩個collection:一個是chunks,用來存儲分塊文件二進制數據;一個是files,用來存儲文件信息(文件名稱等信息)
JAVA代碼:
springboot整合MongoDB
導入jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring‐boot‐starter‐data‐mongodb</artifactId>
</dependency>
application配置
spring:
data:
mongodb:
uri: mongodb://name:password@ip:27017
database: ***
編寫儲存文件測試,這裏返還存儲文件id
此文件id是files集合中的主鍵
可以通過文件id查詢chunks表中的記錄,得到文件的內容
import org.bson.types.ObjectId;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@SpringBootTest
@RunWith(SpringRunner.class)
public class GridFsTest {
@Autowired
private GridFsTemplate gridFsTemplate;
@Test
public void saveTest() throws FileNotFoundException {
File file = new File("******");
FileInputStream fis = new FileInputStream(file);
ObjectId objectId = gridFsTemplate.store(fis, "***");
//打印文件id
System.out.println(objectId.toString());
}
}
讀取文件:
- 配置mongoDB bucket
@Configuration
public class MongoDBConfig {
@Value("${spring.data.mongodb.database}")
private String db;
@Bean
public GridFSBucket getGridFSBucket(MongoClient mongoClient){
//得到mongodb數據庫
MongoDatabase database = mongoClient.getDatabase(db);
//返回bucket
return GridFSBuckets.create(database);
}
}
- 測試讀取文件
@Test
public void getTest() throws IOException {
//根據文件id查詢數據庫
GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is("******")));
//打開下載流對象
GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
//獲取流對象
GridFsResource gridFsResource = new GridFsResource(gridFSFile, downloadStream);
//得到有數據流
InputStream inputStream = gridFsResource.getInputStream();
}
以上,mongoDB的gridFD上傳下載筆記。