欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot集成mongodb,实现文件上传下载

程序员文章站 2022-04-30 23:02:46
...

一、linux上安装mongodb

1、下载安装包:https://www.mongodb.com/download-center#atlas,上传包mongodb-linux-x86_64-rhel70-3.6.5.tgz到服务器

2、创建mongodb文件夹,作为安装目标文件夹

  cd /usr/local;mkdir mongodb

3、解压,移动解压缩后的文件夹下的所有文件到mongodb文件夹下

  tar -zxvf mongodb-linux-x86_64-rhel70-3.6.5.tgz;

  cd mongodb-linux-x86_64-rhel70-3.6.5;

  mv * /usr/local/mongodb

4、创建data/db文件夹存放数据,创建logs文件夹存放日志

  cd /usr/local/mongodb;

  mkdir -p data/db;

  mkdir logs;

5、创建配置文件

  cd /usr/local/mongodb/bin;

  vim mongodb.conf

加入以下内容:

dbpath = /usr/local/mongodb/data/db   
logpath = /usr/local/mongodb/logs/mongodb.log  
port = 27017   
fork = true

bind_ip = 192.168.2.182,127.0.0.1 #多个ip的配置方式

6、启动MongoDB服务

  cd /usr/local/mongodb/bin;

  ./mongod -f mongodb.conf #加载配置文件 

7、客户端访问

  ./mongo

  use wx_applet #创建数据库

  show dbs

  可以看到,我们刚创建的数据库不在数据库的列表中, 要显示它,我们需要向数据库插入一些数据

db.wx_applet.insert({"name":"yangfeng"})

二、springboot整合mongodb,实现文件的上传下载

1、pom.xml文件中加入:

springboot集成mongodb,实现文件上传下载

2、application.properties中加入:

springboot集成mongodb,实现文件上传下载

格式:

spring.data.mongodb.uri=mongodb://username:[email protected]:port/database

3、这里以文件上传到mongodb来做简单的示例

package com.yangfeng.controller.file;

import com.jp.framework.common.model.ServiceResultHelper;
import com.jp.framework.common.util.Constant;
import com.jp.zpzc.entity.customized.FileInfoAO;
import com.jp.zpzc.entity.customized.UserAO;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.InputStream;


/**
 * 文件上传下载
 *
 * @author yangfeng
 * @date 2018-06-04 12:57
 **/
@Controller
@RequestMapping("/file")
public class FileController {


    // 获得SpringBoot提供的mongodb的GridFS对象
    @Autowired
    private GridFsTemplate gridFsTemplate;


    /**
     * 文件上传
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadFile(HttpServletRequest request) throws Exception {
        UserAO user = (UserAO) SecurityUtils.getSubject().getPrincipal();
        Part part = request.getPart("file");
        // 获得提交的文件名
        String fileName = part.getSubmittedFileName();
        // 获得文件输入流
        InputStream ins = part.getInputStream();
        // 获得文件类型
        String contentType = part.getContentType();
        // 将文件存储到mongodb中,mongodb 将会返回这个文件的具体信息
        GridFSFile gridFSFile = gridFsTemplate.store(ins, fileName, contentType);
        FileInfoAO fileInfo = new FileInfoAO();
        fileInfo.setContentType(contentType);
        fileInfo.setFileName(fileName);
        fileInfo.setLastUpdateBy(user != null ? user.getId() : null);
        fileInfo.setMongoFileId(gridFSFile.getId().toString());
        return ServiceResultHelper.genResultWithSuccess(fileInfo);
    }

    /**
     * 下载
     *
     * @param fileId   文件id
     * @param response
     * @return
     */
    @RequestMapping(value = "/downloadFile")
    public void downloadFile(@RequestParam(name = "file_id") String fileId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Query query = Query.query(Criteria.where("_id").is(fileId));
        // 查询单个文件
        GridFSDBFile gfsfile = gridFsTemplate.findOne(query);
        if (gfsfile == null) {
            return;
        }
        String fileName = gfsfile.getFilename().replace(",", "");
        //处理中文文件名乱码
        if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||
                request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")
                || request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            //非IE浏览器的处理:
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        // 通知浏览器进行文件下载
        response.setContentType(gfsfile.getContentType());
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        gfsfile.writeTo(response.getOutputStream());
    }

    /**
     * 删除文件
     *
     * @param fileId
     * @return
     */
    @RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
    @ResponseBody
    public Object deleteFile(@RequestParam(name = "file_id") String fileId) {
        Query query = Query.query(Criteria.where("_id").is(fileId));
        // 查询单个文件
        GridFSDBFile gfsfile = gridFsTemplate.findOne(query);
        if (gfsfile == null) {
            return ServiceResultHelper.genResultWithFaild(Constant.ErrorCode.FILE_NOT_EXIST_ERROR_MSG, Constant.ErrorCode.FILE_NOT_EXIST_ERROR);
        }
        gridFsTemplate.delete(query);
        return ServiceResultHelper.genResultWithSuccess();
    }
}