@Test
public void testGridFs() throws FileNotFoundException {
//要存储的文件
File file
= new File(
"
d:/index_banner.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
=
"
5b9c54e264c614237c271a99
"
;
//根据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(
"
5b32480ed3a022164c4d2f92
"
)));
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |