Springboot + MySQL + html 实现文件的上传、存储、下载、删除

这篇具有很好参考价值的文章主要介绍了Springboot + MySQL + html 实现文件的上传、存储、下载、删除。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

实现步骤及效果呈现如下:

1.创建数据库表:

表名:file_test

Springboot + MySQL + html 实现文件的上传、存储、下载、删除,spring boot,mysql,html

存储后的数据:

Springboot + MySQL + html 实现文件的上传、存储、下载、删除,spring boot,mysql,html

2.创建数据库表对应映射的实体类:

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;

/**
 * 文件实体类
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("file_test")
public class File {
    /**
     * 主键id
     */
    @TableId(value = "id",type = IdType.AUTO)
    private Integer id;
    /**
     * 文件名称
     */
    @TableField("file_name")
    private String fileName;
    /**
     * 文件路径
     */
    @TableField("file_path")
    private String filePath;
    /**
     * 上传时间
     */
    @TableField("upload_time")
    private Date uploadTime;
}

  1. 创建数据访问层Mapper(用来写数据库的增删改查SQL)

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fm.model.File;
import org.apache.ibatis.annotations.Mapper;

/**
 * 数据库映射
 * 集成了mybtis-plus  包含了常用的增删改查方法
 */
@Mapper
public interface FileMapper extends BaseMapper<File> {
}

  1. 创建业务层service

import com.baomidou.mybatisplus.extension.service.IService;
import com.fm.model.File;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件业务层
 * 集成了mybatis-plus  里面包含了数据库常用的增删改成方法
 */
public interface FileService extends IService<File> {
    void upload(MultipartFile file);
}

  1. 创建业务实现类serviceImpl

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fm.mapper.FileMapper;
import com.fm.model.File;
import com.fm.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

/**
 * 文件业务实现
 * 集成了mybatis-plus  里面包含了数据库常用的增删改成方法
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {
    @Resource
    private FileMapper fileMapper;

    @Override
    public void upload(MultipartFile file) {
        //获取当前项目所在根目录
        String rootDirectory = System.getProperty("user.dir");
        //如果当前项目根目录不存在(file_manage文件存储)文件夹,
        // 会自动创建该文件夹用于存储项目上传的文件
        java.io.File savaFile = new java.io.File(rootDirectory + "/file_manage项目文件存储/" + file.getOriginalFilename());
        if (!savaFile.getParentFile().exists()) {
            savaFile.getParentFile().mkdirs();
        }
        //如果当前名称的文件已存在则跳过
        if (savaFile.exists()) {
            return;
        }
        try {
            savaFile.createNewFile();
            file.transferTo(savaFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        File file1 = new File();
        file1.setFileName(file.getOriginalFilename());
        file1.setFilePath("/file_manage项目文件存储/" + file.getOriginalFilename());
        file1.setUploadTime(new Date());
        fileMapper.insert(file1);
    }
}

  1. 创建接口层controller(用来写上传、下载、查询列表、删除接口)

import com.fm.model.File;
import com.fm.service.FileService;
import com.fm.util.FileUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 文件接口层
 */
@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileController {

    //文件实现层
    @Resource
    private FileService fileService;


    /**
     * 文件列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public List<File> list(
    ) {
        try {
            List<File> list = fileService.list();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(
            @RequestParam(value = "file") MultipartFile file//文件
    ) {
        try {
            fileService.upload(file);
            return "文件上传成功!";
        } catch (Exception e) {
            e.printStackTrace();
            return "文件上传失败!";
        }
    }

    /**
     * 删除文件
     *
     * @param fileId
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public String delete(
            @RequestParam(value = "fileId") String fileId//文件
    ) {
        try {
            File file = fileService.getById(fileId);
            //获取当前项目所在根目录
            String rootDirectory = System.getProperty("user.dir");
            java.io.File savaFile = new java.io.File(rootDirectory + file.getFilePath());
            //删除保存的文件
            savaFile.delete();
            boolean b = fileService.removeById(fileId);
            if (b){
                return "成功!";
            }
            return "失败!";
        } catch (Exception e) {
            e.printStackTrace();
            return "失败";
        }
    }


    /**
     * 下载文件
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void download(@RequestParam(value = "fileId") String fileId,
                         HttpServletResponse response, HttpServletRequest request
    ) {
        try {
            File file = fileService.getById(fileId);
            if (file != null) {
                //获取当前项目所在根目录
                String rootDirectory = System.getProperty("user.dir");
                //调用自主实现的下载文件工具类中下载文件的方法
                FileUtil.doDownloadFile(rootDirectory + file.getFilePath(), response, request);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("下载文件出错,错误原因:" + e);
        }
    }
}

  1. 文件工具类(用来写下载文件的方法)

/**
 * 文件工具类
 */
public class FileUtil {

    /**
     * 下载文件
     * @param Path
     * @param response
     * @param request
     */
    public static void doDownloadFile(String Path, HttpServletResponse response, HttpServletRequest request) {
        try {
            //关键点,需要获取的文件所在文件系统的目录,定位准确才可以顺利下载文件
            String filePath = Path;
            File file = new File(filePath);
            //创建一个输入流,将读取到的文件保存到输入流
            InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 重要,设置responseHeader
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes()));
            response.setHeader("Content-Length", "" + file.length());
            //octet-stream是二进制流传输,当不知文件类型时都可以用此属性
            response.setContentType("application/octet-stream");
            //跨域请求,*代表允许全部类型
            response.setHeader("Access-Control-Allow-Origin", "*");
            //允许请求方式
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            //用来指定本次预检请求的有效期,单位为秒,在此期间不用发出另一条预检请求
            response.setHeader("Access-Control-Max-Age", "3600");
            //请求包含的字段内容,如有多个可用哪个逗号分隔如下
            response.setHeader("Access-Control-Allow-Headers", "content-type,x-requested-with,Authorization, x-ui-request,lang");
            //访问控制允许凭据,true为允许
            response.setHeader("Access-Control-Allow-Credentials", "true");
            //创建一个输出流,用于输出文件
            OutputStream oStream = new BufferedOutputStream(response.getOutputStream());
            //写入输出文件
            oStream.write(buffer);
            oStream.flush();
            oStream.close();
        } catch (Exception e) {
            System.out.println("下载日志文件出错,错误原因:" + e);
        }
    }
}

Pom文件依赖

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.12.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.fm</groupId>
    <artifactId>file_manage</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>file_manage</name>
    <description>file_manage</description>
    <properties>
        <java.version>22</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

<!--        mysql依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>
<!--        jdbc依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
<!--        mybatis-plus依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>

<!--        JSON依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.70</version>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

yml配置文件:

#数据库连接配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/file_test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false
    username: root
    password:

  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    #    joda-date-time-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8


  thymeleaf:
    prefix: classpath:/static
    suffix: .html
    cache: false

#启动端口
server:
  port: 8100

Html前端静态页面(内置在springboot项目中可直接运行):

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
</head>
<html lang="en">
<body>
<div id="app">
    <div class="container-fluid">
        <!--标题行-->
        <div class="row">
            <div align="center" class="col-sm-6 col-sm-offset-3"><button style="font-size: 18px;float: right" href="" class="btn btn-info btn-sm" @click.prevent="uploadFile()">上传文件</button><h1 class="text-center">文件列表</h1></div>
        </div>
        <!--数据行-->
        <div class="row">
            <div class="col-sm-10 col-sm-offset-1">
                <!--列表-->
                <table class="table table-striped table-bordered" style="margin-top: 10px;">
                    <tr>
                        <td align="center" style="font-size: 18px;">文件名称</td>
                        <td align="center" style="font-size: 18px;">文件路径</td>
                        <td align="center" style="font-size: 18px;">上传时间</td>
                        <td align="center" style="font-size: 18px;">操作</td>
                    </tr>
                    <tr v-for="user in list">
                        <td style="font-size: 18px;">{{user.fileName}}</td>
                        <td style="font-size: 18px;">{{user.filePath}}</td>
                        <td style="font-size: 18px;">{{user.uploadTime}}</td>
                        <td>
                            <button style="font-size: 18px;" href=" " class="btn btn-info btn-sm" @click="deleteFile(user.id)">删除</button>
                            <a style="font-size: 18px;" href=" " class="btn btn-info btn-sm" @click="downloadFile(user.id)">下载</a>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
</div>


<!-- 弹出选择文件表单 -->
<div id="my_dialog" class="my-dialog" style="display: none">
    <h3>需要上传的文件</h3>
    <form id="form1" action="http://localhost:8100/file/upload" target="form1" method="post" enctype="multipart/form-data">
        <input type="file" name="file" accept=".jpg,.png,.gif">
        <button type="button" style="font-size: 18px;" onclick="upload()">提交</button>
        <button type="button" style="font-size: 18px;" onclick="cancelFile()">取消</button>
    </form>
</div>



<style type="text/css">
    .container-fluid {
        width: 650px;
    //height: 200px;
    //background-color: orchid;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
    }

    .my-dialog {
        width: 300px;
    //height: 200px;
    //background-color: orchid;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
    }


</style>


</body>
</html>
<!--引入jquery-->
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<!--引入axios-->
<script src="js/axios.min.js"></script>
<!--引入vue-->
<script src="js/vue.js"></script>
<script>
    var app = new Vue({
        el: "#app",
        data:{
            msg:"vue 生命周期",
            list:[], //定义一个list空数组,用来存贮所有文件的信息
        },
        methods:{
            uploadFile(){  //文件选择
                /*悬浮窗口的显示,需要将display变成block*/
                document.getElementById("my_dialog").style.display = "block";
                /*将列表隐藏*/
                document.getElementById("app").style.display = "none";
            },

            deleteFile(id){
                /*alert("删除!");*/
                console.log("打印数据"+id);

                axios.delete('http://localhost:8100/file/delete',{
                    params:{
                        fileId:id,
                    },
                }).then(response=>{

                    console.log("回调--->>>"+response.data);

                    if (response.data == "成功!") {
                        alert("删除成功!");
                        //跳转到显示页面
                        //document.referrer 前一个页面的URL  返回并刷新页面
                        location.replace(document.referrer);
                    } else {
                        alert("删除失败!");
                        //document.referrer 前一个页面的URL  返回并刷新页面
                        location.replace(document.referrer);
                    }
                })
            },

            downloadFile(id){
                window.open("http://localhost:8100/file/download?fileId="+id);

            },

        },
        computed:{

        },
        created(){ //执行 data methods computed 等完成注入和校验
            //发送axios请求
            axios.get("http://localhost:8100/file/list").then(res=>{
                console.log(res.data);
                this.list = res.data;
            }); //es6 箭头函数 注意:箭头函数内部没有自己this  简化 function(){} //存在自己this
        },
    });


    cancelFile=function(){ //返回首页
        /*浮窗口隐藏*/
        document.getElementById("my_dialog").style.display = "none";
        /*将列表显示*/
        document.getElementById("app").style.display = "block";

    };

    function upload() {
        /*alert('文件上传成功!');*/
        $("#form1").submit();

        //document.referrer 前一个页面的URL  返回并刷新页面
        location.replace(document.referrer);

    }
</script>

运行效果:

Springboot + MySQL + html 实现文件的上传、存储、下载、删除,spring boot,mysql,html

上传文件:

Springboot + MySQL + html 实现文件的上传、存储、下载、删除,spring boot,mysql,html

选择文件:

Springboot + MySQL + html 实现文件的上传、存储、下载、删除,spring boot,mysql,html

提交成功后;

Springboot + MySQL + html 实现文件的上传、存储、下载、删除,spring boot,mysql,html

列表新增一条数据:

Springboot + MySQL + html 实现文件的上传、存储、下载、删除,spring boot,mysql,html

点击下载选择保存位置:

Springboot + MySQL + html 实现文件的上传、存储、下载、删除,spring boot,mysql,html

点击删除后:

Springboot + MySQL + html 实现文件的上传、存储、下载、删除,spring boot,mysql,html

点击确定文件列表删除一条数据:

Springboot + MySQL + html 实现文件的上传、存储、下载、删除,spring boot,mysql,html

html静态页面需要js等文件,会放在完整项目里面,有需要的朋友自取。

      

完整素材及全部代码

   代码已上传csdn,0积分下载,觉得这片博文有用请留下你的点赞,有问题的朋友可以一起交流讨论。

https://download.csdn.net/download/xuezhe5212/89238404
 文章来源地址https://www.toymoban.com/news/detail-861765.html

到了这里,关于Springboot + MySQL + html 实现文件的上传、存储、下载、删除的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot 如何实现文件上传和下载

    当今Web应用程序通常需要支持文件上传和下载功能,Spring Boot提供了简单且易于使用的方式来实现这些功能。在本篇文章中,我们将介绍Spring Boot如何实现文件上传和下载,同时提供相应的代码示例。 Spring Boot提供了Multipart文件上传的支持。Multipart是HTTP协议中的一种方式,用

    2024年02月15日
    浏览(19)
  • SpringBoot整合Minio实现文件上传、下载

    SpringBoot整合Minio实现文件上传、下载: 1,介绍高性能分布式存储文件服务Minio:Minio是 基于Go语言编写的对象存储服务 , 适合于存储大容量非结构化的数据 ,例如 图片、音频、视频、日志文件、备份数据和容器/虚拟机镜像等 ,而一个对象文件可以是任意大小,从几kb到最

    2024年02月06日
    浏览(25)
  • SpringBoot整合Hutool实现文件上传下载

    我相信我们在日常开发中,难免会遇到对各种媒体文件的操作,由于业务需求的不同对文件操作的代码实现也大不相同 maven配置 文件类 文件接口  配置静态资源映射

    2024年02月02日
    浏览(34)
  • springboot+微信小程序实现文件上传下载(预览)pdf文件

    实现思路: 选择文件 wx.chooseMessageFile ,官方文档: https://developers.weixin.qq.com/miniprogram/d e v/api/media/image/wx.chooseMessageFile.html 上传文件 `wx,uploadFile` , 官方文档:https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html 查看所有上传的pdf文件,显示在页面上 点击pdf文件

    2024年02月08日
    浏览(30)
  • SpringBoot实现文件上传和下载笔记分享(提供Gitee源码)

    前言:这边汇总了一下目前SpringBoot项目当中常见文件上传和下载的功能,一共三种常见的下载方式和一种上传方式,特此做一个笔记分享。 目录 一、pom依赖 二、yml配置文件 三、文件下载

    2024年02月11日
    浏览(23)
  • SpringBoot-集成FTP(上传、下载、删除)

    目录 一、引入依赖 二、配置文件 三、Controller层 四、Service层 五、相关工具类 由于服务在内网部署,需要使用ftp服务器管理文件,总结如下 一、引入依赖 Tip: 使用commons-net 3.9.0版本,之前的版本有漏洞 二、配置文件 配置文件类: 三、Controller层 Tip: Response为通用返回类,

    2024年02月12日
    浏览(70)
  • 基于SpringBoot实现文件上传和下载(详细讲解And附完整代码)

    目录 一、基于SpringBoot实现文件上传和下载基于理论 二、详细操作步骤 文件上传步骤: 文件下载步骤: 三、前后端交互原理解释  四、小结  博主介绍:✌专注于前后端领域开发的优质创作者、秉着互联网精神开源贡献精神,答疑解惑、坚持优质作品共享。本人是掘金/腾讯

    2024年04月11日
    浏览(33)
  • 一张图带你学会入门级别的SpringBoot实现文件上传、下载功能

    🧑‍💻作者名称:DaenCode 🎤作者简介:啥技术都喜欢捣鼓捣鼓,喜欢分享技术、经验、生活。 😎人生感悟:尝尽人生百味,方知世间冷暖。 📖所属专栏:SpringBoot实战 标题 一文带你学会使用SpringBoot+Avue实现短信通知功能(含重要文件代码) 一张思维导图带你学会Springboot创

    2024年02月12日
    浏览(35)
  • 【java】java实现大文件的分片上传与下载(springboot+vue3)

    源码: https://gitee.com/gaode-8/big-file-upload 演示视频 https://www.bilibili.com/video/BV1CA411f7np/?vd_source=1fe29350b37642fa583f709b9ae44b35 对于超大文件上传我们可能遇到以下问题 • 大文件直接上传,占用过多内存,可能导致内存溢出甚至系统崩溃 • 受网络环境影响,可能导致传输中断,只能重

    2024年02月02日
    浏览(32)
  • Spring Boot 中实现文件上传、下载、删除功能

    🏆作者简介,普修罗双战士,一直追求不断学习和成长,在技术的道路上持续探索和实践。 🏆多年互联网行业从业经验,历任核心研发工程师,项目技术负责人。 🎉欢迎 👍点赞✍评论⭐收藏 🔎 SpringBoot 领域知识 🔎 链接 专栏 SpringBoot 专业知识学习一 SpringBoot专栏 Sprin

    2024年01月19日
    浏览(24)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包