MongoDB文件存储GridFS学习
程序员文章站
2022-04-30 23:29:37
...
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:[email protected]: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上传下载笔记。