spingboot mongoDB实现文件的上传、下载、预览

pom.xml

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.file</groupId>
    <artifactId>FileService</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>FileService</name>
    <description>FileService</description>
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.5.14</spring-boot.version>
    </properties>
    <dependencies>

        <!-- io常用工具类 -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.1.1.RELEASE</version>                <configuration>
                    <mainClass>com.file.FileServiceApplication</mainClass>
                    <skip>false</skip>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

Controller

复制代码
package com.file.controller;

import com.file.utils.MongoDBGridFs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private MongoDBGridFs mongoDBGridFs;

    @Autowired
    private MongoTemplate mongoTemplate;

    //文件上传
    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
        return mongoDBGridFs.saveFile(file);
    }

    @GetMapping("/download")
    public void download(boolean online,String fileId, HttpServletResponse response){
        mongoDBGridFs.getFile(online,fileId,response);
    }

    @PostMapping("/del")
    public String del(@RequestParam("fileId") String fileId){
        mongoDBGridFs.deleteFile(fileId);
        return "删除文件成功";
    }

    @GetMapping("/findAll")
    public Object findALl(){
        return  mongoDBGridFs.findAll();
    }


}
复制代码
工具类:MongoDBGridFs
复制代码
package com.file.utils;


import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
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.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Component
public class MongoDBGridFs {
    @Autowired
    private GridFsTemplate gridFsTemplate;

    //将Workbook文件转换成file文件
//    public MultipartFile workbookToMultipartFile(Workbook workbook, String fileName) throws IOException {
//        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//        workbook.write(outputStream);
//        byte[] bytes = outputStream.toByteArray();
//        return new MockMultipartFile(fileName, fileName, null, bytes);
//    }

    //上传文件
    // 保存文件
    public String saveFile(MultipartFile file) throws IOException {
        // 新文件名
        String originalFilename = file.getOriginalFilename();
        // 获得文件输入流
        InputStream ins = file.getInputStream();
        // 获得文件类型
        String contentType = file.getContentType();

        // 将文件存储到mongodb中,mongodb将会返回这个文件的具体信息
//        ObjectId objectId = gridFsTemplate.store(ins, originalFilename, contentType);

        // 上传文件中我们也可以使用DBObject附加一些属性
        DBObject metadata = new BasicDBObject();
        //metadata.put("hello","word");

        ObjectId objectId = gridFsTemplate.store(ins, originalFilename, contentType, metadata);

        return objectId.toString();
    }

    // 下载文件
    public void getFile(boolean online,String id, HttpServletResponse response) {
        GridFsResource resource = null;
        try {
            // 根据文件ID从GridFS中获取文件
            GridFSFile file = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id)));
            if (file != null) {
                // 设置响应头信息
                String filename = URLEncoder.encode(file.getFilename(), "UTF-8");
                String contentType = file.getMetadata().getString("contentType");
                response.setContentType(contentType);
                if(online){
                    response.setHeader("Content-Disposition", "attachment; filename=" + filename);
                }
                // 从GridFS中获取文件流并写入响应输出流
                resource = gridFsTemplate.getResource(file);
                try (InputStream inputStream = resource.getInputStream();
                     BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {
                    IOUtils.copy(inputStream, outputStream);
                    // 刷新响应缓冲区
                    response.flushBuffer();
                }
            } else {
                // 文件不存在,返回空响应
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void deleteFile(String fileId){
        //根据文件id删除fs.files和fs.chunks中的记录

        gridFsTemplate.delete(Query.query(Criteria.where("_id").is(fileId)));
    }


    public List<GridFSFile> findAll(){

        List<GridFSFile> files =gridFsTemplate.find(new Query()).into(new ArrayList<>());

// 打印文件信息
        for (GridFSFile file : files) {
            System.out.println("文件ID: " + file.getObjectId());
            System.out.println("文件名称: " + file.getFilename());
            System.out.println("文件大小: " + file.getLength());
            System.out.println("上传时间: " + file.getUploadDate());
            System.out.println("----------------------------");
        }


        return files;
    }

}

application.properties

复制代码
# åºç¨æå¡ WEB 访é®ç«¯å£
server.port=9092
# Spring??
spring.data.mongodb.database=test
spring.data.mongodb.uri=mongodb://1ocalhost:27017/
#    uri: mongodb://localhost:27017/

感兴趣的朋友 可以在网盘里下载,整个项目都放在里面了
通过百度网盘分享的文件:FileService.zip
链接:https://pan.baidu.com/s/11SqbIfpMwG8gBRK8Y1xeQg?pwd=ui9i 
提取码:ui9i
相关推荐
远歌已逝1 小时前
维护在线重做日志(二)
数据库·oracle
qq_433099402 小时前
Ubuntu20.04从零安装IsaacSim/IsaacLab
数据库
Dlwyz2 小时前
redis-击穿、穿透、雪崩
数据库·redis·缓存
工业甲酰苯胺4 小时前
Redis性能优化的18招
数据库·redis·性能优化
没书读了5 小时前
ssm框架-spring-spring声明式事务
java·数据库·spring
i道i5 小时前
MySQL win安装 和 pymysql使用示例
数据库·mysql
小怪兽ysl5 小时前
【PostgreSQL使用pg_filedump工具解析数据文件以恢复数据】
数据库·postgresql
wqq_9922502776 小时前
springboot基于微信小程序的食堂预约点餐系统
数据库·微信小程序·小程序
爱上口袋的天空6 小时前
09 - Clickhouse的SQL操作
数据库·sql·clickhouse
聂 可 以8 小时前
Windows环境安装MongoDB
数据库·mongodb