<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
GridfsTest.java
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.commons.io.IOUtils;
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.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class GridfsTest {
@Autowired
private GridFsTemplate gridFsTemplate;
@Autowired
private GridFSBucket gridFSBucket;
@Test
public void uploadFile() throws FileNotFoundException {
String pdfPath = "D:\\pdfRender\\古代埃及文明 封面.pdf";
File file = new File(pdfPath);
// 获得提交的文件名
String fileName = file.getName();
// 获得文件输入流
InputStream ins = new FileInputStream(file);
// 获得文件类型
String contentType = "pdf";
// 将文件存储到mongodb中,mongodb 将会返回这个文件的具体信息
ObjectId objectId = gridFsTemplate.store(ins, fileName, contentType);
}
@Test
public void download() throws IOException {
String id="5eeb4bdfa610dd4b54583265";
String md5="f3976c520026d2287c3746f4bc84f91e";
//根据id查询文件
GridFSFile gridFSFile =
gridFsTemplate.findOne(Query.query(Criteria.where("md5").is(md5)));
//打开流下载对象
GridFSDownloadStream downloadStream =
gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
//获取流对象
GridFsResource gridFsResource=new GridFsResource(gridFSFile,downloadStream);
String pdfPath = "D:\\pdfRender\\古代埃及文明 封面 download.pdf";
File file = new File(pdfPath);
OutputStream output = new FileOutputStream(file);
IOUtils.copy(gridFsResource.getInputStream(), output);
output.close();
}
}
本文介绍如何使用Java操作MongoDB的GridFS存储系统,详细讲解GridfsTest.java代码示例,涵盖文件上传、下载及管理操作。
961

被折叠的 条评论
为什么被折叠?



