java mongodb gridfs_MongoDB-4 GridFS 文件存储

1. 配置config

spring:

data:

mongodb:

uri: mongodb://username:password@192.168.2.72:27017

database: mydb

@Component

public class WebConfig {

@Value("${spring.data.mongodb.database}")

private String mongodb;

@Bean

public GridFSBucket getGridFSBucket(MongoClient mongoClient){

MongoDatabase database = mongoClient.getDatabase(mongodb);

GridFSBucket bucket = GridFSBuckets.create(database);

return bucket;

}

}

2. 基于gridfs的上传,读取与下载

@Autowired

private GridFSBucket gridFSBucket;

/**

* 创建文件到GirdFS

* @param model

* @return

* @throws Exception

*/

@GetMapping("/addToGridFS")

@ResponseBody

public Object addToGirdFS(Model model) throws Exception {

// 声明freemarker的配置类

Configuration cfg = new Configuration(Configuration.getVersion());

// 声明freemarker模板所需要加载的目录位置

String classpath = this.getClass().getResource("/").getPath();

cfg.setDirectoryForTemplateLoading(new File(classpath + "templates"));

// System.out.println(classpath + "templates");

// 构建数据

model = makeModel(model);

// 加载ftl模板

Template template = cfg.getTemplate("user.ftl", "utf-8");

// 获得静态化后的内容

String htmlContent = FreeMarkerTemplateUtils.processTemplateIntoString(template, model.asMap());

InputStream inputStream = IOUtils.toInputStream(htmlContent);

// 上传

ObjectId fileId = gridFSBucket.uploadFromStream("1001.html", inputStream);

System.out.println("上传完成。 文件ID:" + fileId);

// 文件在mongodb中的id

return fileId.toString();

}

/**

* 读取文件

* @param model

* @return

* @throws Exception

*/

@GetMapping("/readGridFS")

@ResponseBody

public String readGridFS(Model model) throws Exception {

// 获取文件ID

String objectId = "5e42924980fb940ab75f141a"; // 根据upload后文件ID修改

// 获取内容

GridFSFindIterable gridFSFindIterable = gridFSBucket.find(Filters.eq("_id", new ObjectId(objectId)));

GridFSFile gridFSFile = gridFSFindIterable.first();

System.out.println("filename: " + gridFSFile.getFilename());

return gridFSFile.getFilename();

}

/**

* 从gridfs中下载文件

* @throws Exception

*/

@GetMapping("/downloadGridFS")

@ResponseBody

public String downloadGridFS() throws Exception {

// 获取文件ID

String objectId = "5e42924980fb940ab75f141a";

// 获取文件流,定义存放位置和名称

File file = new File(htmlTarget + "/1001.html");

// 创建输出流

OutputStream os = new FileOutputStream(file);

// 执行下载

gridFSBucket.downloadToStream(new ObjectId(objectId), os);

System.out.println("下载成功");

return "ok";

}

@GetMapping("/downloadGridFSByFileName")

@ResponseBody

public String downloadGridFSByFileName() throws Exception {

// 获取文件ID

String filename = "1001.html";

// 获取文件流,定义存放位置和名称

File file = new File(htmlTarget + "/" + filename);

// 创建输出流

OutputStream os = new FileOutputStream(file);

// 执行下载

gridFSBucket.downloadToStream(filename, os);

System.out.println("下载成功");

return "ok";

}

/**

* 删除文件

* @param model

* @return

* @throws Exception

*/

@GetMapping("/deleteGirdFS")

@ResponseBody

public String deleteGirdFS(Model model) throws Exception {

// 获取文件ID

String objectId = "5e42924980fb940ab75f141a";

// 执行删除

gridFSBucket.delete(new ObjectId(objectId));

return "ok";

}

5. 整合SpringBoot作为文件服务展示

当然也能和nginx放在一起使用

/**

* 借助nginx+springboot来访问gridfs中的文件内容

* @param fileName

* @return

* @throws Exception

*/

@GetMapping("/detail/{fileName}")

public void detail(@PathVariable("fileName") String fileName, HttpServletResponse response) throws Exception {

response.setContentType("text/html;charset=utf-8");

ServletOutputStream outputStream = null;

try {

outputStream = response.getOutputStream();

gridFSBucket.downloadToStream(fileName, outputStream);

// 方式2

// GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(fileName);

// GridFsResource gridFsResource = new GridFsResource(gridFSDownloadStream.getGridFSFile(), gridFSDownloadStream);

// String data = IOUtils.toString(gridFsResource.getInputStream(), "UTF-8");

// System.out.println(data);

// out.write(data.getBytes("UTF-8"));

// out.write("风间影月".getBytes("UTF-8"));

} finally {

outputStream.close();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值