[实战]SpringBoot操作MongoDB Gridfs

使用spring-data-mongod把文件存入mongodb gridfs,
并实现增删查。

首先新建一个springboot项目
文件结构如下

image.png

在application.properties配置mongodb的database

image.png

核心代码

GridfsService代码

package com.awlsx.gridfsdemo;

import com.mongodb.BasicDBObject;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;

@Service
public class GridfsService {



    @Autowired
    private MongoDbFactory mongodbfactory;


    /**
     * 插入文件
     * @param file
     * @return
     */
    public GridFSInputFile save(MultipartFile file){

        GridFS gridFS = new GridFS(mongodbfactory.getDb());

        try{

            InputStream in = file.getInputStream();

            String name = file.getOriginalFilename();

            GridFSInputFile gridFSInputFile = gridFS.createFile(in);

            gridFSInputFile.setFilename(name);

            gridFSInputFile.setContentType(file.getContentType());

            gridFSInputFile.save();
            return gridFSInputFile;
        }
        catch (Exception e){}

        return null;

    }

    /**
     * 据id返回文件
     */
    public GridFSDBFile getById(ObjectId id){

        GridFS gridFS = new GridFS(mongodbfactory.getDb());

        return gridFS.findOne(new BasicDBObject("_id", id));

    }


    /**
     * 删除
     * @param id
     */
    public void remove(String id) {
        GridFS gridFS = new GridFS(mongodbfactory.getDb());
        gridFS.remove(new ObjectId(id));
    }

}

Controller文件代码

package com.awlsx.gridfsdemo;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@RestController
public class Controller {

    @Autowired
    private GridfsService gridfsService;

    @RequestMapping(value = "/file/upload")
    public Object uploadData(@RequestParam(value = "file")MultipartFile file) {

        GridFSInputFile inputFile = gridfsService.save(file);

        if (inputFile == null) {
            return "upload fail";
        }
        String id = inputFile.getId().toString();
        String md5 = inputFile.getMD5();
        String name = inputFile.getFilename();
        long length = inputFile.getLength();

        Map dt = new HashMap();
        dt.put("id",id);
        dt.put("md5",md5);
        dt.put("name",name);
        dt.put("length",length);

        return dt;
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping(value = "/file/delete", method = RequestMethod.POST)
    public Object deleteFile(@RequestParam(value = "id") String id) {

//        删除文件
        gridfsService.remove(id);
        return "delete ok";
    }


    /**
     * 下载文件
     * @param id
     * @param response
     */
    @RequestMapping(value = "/file/{id}", method = RequestMethod.GET)
    public void getFile(@PathVariable String id, HttpServletResponse response) {
        GridFSDBFile file = gridfsService.getById(new ObjectId(id));

        if (file == null) {
            responseFail("404 not found",response);
            return;
        }

        OutputStream os = null;

        try {
            os = response.getOutputStream();
            response.addHeader("Content-Disposition", "attachment;filename=" + file.getFilename());
            response.addHeader("Content-Length", "" + file.getLength());
            response.setContentType("application/octet-stream");
            file.writeTo(os);
            os.flush();
            os.close();

        } catch (Exception e) {
            try{
                if (os != null) {
                    os.close();
                }
            }catch (Exception e2){}
            e.printStackTrace();
        }

    }

    @RequestMapping(value = "/file/view/{id}", method = RequestMethod.GET)
    public void viewFile(@PathVariable String id, HttpServletResponse response) {

        GridFSDBFile file = gridfsService.getById(new ObjectId(id));

        if (file == null) {
            responseFail("404 not found",response);
            return;
        }

        OutputStream os = null;

        try {
            os = response.getOutputStream();
            response.addHeader("Content-Disposition", "attachment;filename=" + file.getFilename());
            response.addHeader("Content-Length", "" + file.getLength());
            response.setContentType(file.getContentType());
            file.writeTo(os);
            os.flush();
            os.close();

        } catch (Exception e) {
            try{
                if (os != null) {
                    os.close();
                }
            }catch (Exception e2){}
            e.printStackTrace();
        }

    }

    private void responseFail(String msg,HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        ObjectMapper mapper = new ObjectMapper();
        try{
            String res = mapper.writeValueAsString(msg);
            out = response.getWriter();
            out.append(res);
        } catch (Exception e){
            try {
                if (out != null) {
                    out.close();
                }
            }catch (Exception e2) {}
        }
    }


}

运行程序

先上传文件

image.png
image.png

预览文件

image.png

下载文件

把链接贴到浏览器地址栏,发现文件已经下载下来了。

image.png

删除文件,成功

image.png

查看数据库,发现数据库中多了两个collection

db.png

查看数据库中fs.files,文件已经成功被删除


image.png

项目代码

https://gitee.com/jetviper/springboot-mongodb-fridfs

你可能感兴趣的:([实战]SpringBoot操作MongoDB Gridfs)