服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 使用Springboot整合GridFS实现文件操作

使用Springboot整合GridFS实现文件操作

2022-02-26 00:28积木i Java教程

这篇文章主要介绍了使用Springboot整合GridFS实现文件操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

GridFsOperations,实现GridFS文件上传下载删除

最近学习GridFS,想用它整合springboot弄个文件的上传下载。

网上查到的很多资料都是使用GridFsTemplate,还有GridFSBucket来实现的,需要各种额外配置Bean。但是看了spring-data-mongodb的官方文档,以及示例代码,他们只用到了GridFsOperations,无需其他任何配置。

然后就用GridFsOperations写了个文件上传下载的demo,用起来还是很方便的,给大家个参考。

上传下载删除功能实现

pom.xml

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

application.properties

#文件上传下载配置
spring.servlet.multipart.max-file-size=1024MB
spring.servlet.multipart.max-request-size=1024MB

FileController

package com.example.tryRedis.controller;
import static org.springframework.data.mongodb.core.query.Query.*;
import static org.springframework.data.mongodb.gridfs.GridFsCriteria.*;
import com.mongodb.client.gridfs.model.GridFSFile;
import io.swagger.v3.oas.annotations.Parameter;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/file")
public class FileController {
  @Autowired
  GridFsOperations gridFsOperations;
  //上传文件
  @PostMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  public Map<String , ObjectId> upload(@Parameter @RequestPart(value = "file") MultipartFile file){
      //开始时间
      long begin = System.nanoTime();
      Map<String,ObjectId> map = new HashMap<>();
      try{
          InputStream streamForUpload = file.getInputStream();
          ObjectId objectId = gridFsOperations.store(streamForUpload,file.getOriginalFilename(),file.getContentType());
          //上传结束
          long end = System.nanoTime();
          long time = end-begin;
          System.out.println("本次上传共耗时: "+ time);
          System.out.println("上传成功!文件名: "+file.getOriginalFilename()+". 文件ID: "+objectId);
          map.put(file.getOriginalFilename(),objectId);
      }catch (Exception e){
          e.printStackTrace();
      }
      return map;
  }
  //查询并下载文件
  @GetMapping("/download")
  public String download(String filename, HttpServletResponse response) throws IOException {
      //开始时间
      long begin = System.nanoTime();
      //查询文件
      GridFSFile result  = gridFsOperations.findOne(query(whereFilename().is(filename)));
      GridFsResource gridFsResource= gridFsOperations.getResource(result);
      String contentType = gridFsResource.getContentType();
      System.out.println("contentType: "+contentType);
      System.out.println("filename: "+gridFsResource.getFilename());
      response.reset();
      response.setContentType(contentType);
      //注意: 如果没有下面这行设置header, 结果会将文件的内容作为响应的 body 直接输出在页面上, 而不是下载文件
      response.setHeader("Content-Disposition","attachment;filename="+filename);  //指定下载文件名
      ServletOutputStream outputStream = response.getOutputStream();
      InputStream is = gridFsResource.getInputStream();
      byte[] bytes = new byte[1024];
      int len = 0;
      while ((len=is.read(bytes))!=-1){
          outputStream.write(bytes,0,len);
      }
      is.close();
      outputStream.close();
      //下载结束
      long end = System.nanoTime();
      long time = end-begin;
      System.out.println("本次下载共耗时: "+ time);
      return contentType;
  }
  @DeleteMapping("/delete")
  public String deleteFile(@Parameter @RequestParam("filename") String filename){
      gridFsOperations.delete(query(whereFilename().is(filename)));
      return "delete success";
  }
}

 

测试

上传

使用Springboot整合GridFS实现文件操作 使用Springboot整合GridFS实现文件操作

下载

红色圈内点击download就可以下载啦。或者在地址栏直接输入localhost:8080/file/download?filename=todo.txt 也可以直接下载文件(这里的todo.txt是我测试的文件,你们填自己上传的文件名,不要忘了加上后缀名!)

使用Springboot整合GridFS实现文件操作

删除

使用Springboot整合GridFS实现文件操作

上面这些上传删除功能测试的时候,大家也可以结合mongodb的数据库去看看。

使用Springboot整合GridFS实现文件操作

上传的文件类型不限,大小嘛,看你properties文件里设置的上限是多大了。我拿700MB的文件上传了也ok,然后在数据库中会被分成很多个块进行存储。具体存储的细节和原理,网上文档很多,这儿就不唠叨嘞。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/Lao_gan_ma/article/details/117295052

延伸 · 阅读

精彩推荐