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
相关推荐
明矾java11 分钟前
Mysql-SQL执行流程解析
数据库·sql·mysql
蓬莱道人27 分钟前
BenchmarkSQL使用教程
数据库
p@nd@42 分钟前
Oracle筑基篇-调度算法-LRU的引入
数据库·oracle·操作系统·lru
来一杯龙舌兰1 小时前
【MongoDB】使用 MongoDB 存储日志、审批、MQ等数据的案例及优点
数据库·mongodb
技术路上的苦行僧1 小时前
分布式专题(8)之MongoDB存储原理&多文档事务详解
数据库·分布式·mongodb
孤独的履行者1 小时前
入门靶机:DC-1的渗透测试
数据库·python·网络安全
wy02_1 小时前
MySQL-MVCC(多版本并发控制)
数据库·mysql
NY63 小时前
mysql运维篇笔记——日志,主从复制,分库分表,读写分离
数据库·sql
潜洋3 小时前
Spring Boot 教程之三十六:实现身份验证
java·数据库·spring boot
科马3 小时前
【Redis】缓存
数据库·redis·spring·缓存