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
相关推荐
小码的头发丝、36 分钟前
Django中ListView 和 DetailView类的区别
数据库·python·django
Karoku0661 小时前
【企业级分布式系统】Zabbix监控系统与部署安装
运维·服务器·数据库·redis·mysql·zabbix
周全全1 小时前
MySQL报错解决:The user specified as a definer (‘root‘@‘%‘) does not exist
android·数据库·mysql
白云如幻1 小时前
MySQL的分组函数
数据库·mysql
荒川之神2 小时前
ORACLE 闪回技术简介
数据库·oracle
时差9533 小时前
【面试题】Hive 查询:如何查找用户连续三天登录的记录
大数据·数据库·hive·sql·面试·database
让学习成为一种生活方式3 小时前
R包下载太慢安装中止的解决策略-R语言003
java·数据库·r语言
秋意钟4 小时前
MySQL日期类型选择建议
数据库·mysql
Dxy12393102164 小时前
python下载pdf
数据库·python·pdf
桀桀桀桀桀桀5 小时前
数据库中的用户管理和权限管理
数据库·mysql