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";
    }

}

测试:

上传

在这里插入图片描述
在这里插入图片描述

下载

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

删除

在这里插入图片描述

上面这些上传删除功能测试的时候,大家也可以结合mongodb的数据库去看看。
在这里插入图片描述

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

ok,到这儿就结束了。有问题欢迎在评论区交流哈!一起进步!

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值