使用GridFS进行数据流的分段存储。
若使用maven项目,pom.xml引入依赖:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mongodb/mongodb-driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.12.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.14</version>
</dependency>
MongoClient mongoClient = new MongoClient("192.168.1.104", 27017);
DB database = mongoClient.getDB("test");
GridFS fs = new GridFS( database);
GridFSInputFile gridFSInputFile = fs.createFile(new File("H:\\PythonWorkspace\\FaceDataDeal\\img\\1.jpg"));
gridFSInputFile.setFilename("1.jpg");
gridFSInputFile.setId("1.jpg");
gridFSInputFile.save();
GridFSInputFile gridFSInputFile2 = fs.createFile(new File("H:\\PythonWorkspace\\FaceDataDeal\\img\\1.jpg"));
gridFSInputFile2.setFilename("2.jpg");
gridFSInputFile2.setId("2.jpg");
gridFSInputFile2.save();
生成fs.files和fs.chunks文件。
fs.files:存储的是每一个上传到数据库的文档的信息
fs.chunks:存储的是上传文件的内容。一个文件可能被拆分成几行有序的chunks数据存储
如果要在添加其他的信息可以使用**gridFSInputFile.put(key,value)**方法
附:如果要在另一个表中每行存储多个该文件的data信息,可以在上方代码的基础上用如下方法:
DBCollection collection = database.getCollection("tb_json");
Document document1 = new Document();
Document document2 = new Document();
document2.append("files_id",gridFSInputFile.getId());
// document2.append("blob" ,gridFSInputFile.getAliases());
document1.append("chip" , document2);
Document document3 = new Document();
document3.append("files_id",gridFSInputFile2.getId());
// document3.append("blob" ,gridFSInputFile2.getMetaData());
document1.append("idCard" ,document3 );
document1.append("probe2" ,document2 );
document.append("_id","1707821993100414");
document.append("sex","male");
document.append("country","America");
document.append("age",10);
document.append("image", document1);
collection.insert((DBObject) JSON.parse(document.toJson()));
结果:
使用主表中的files_id进行表关联: