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

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

1.创建数据库表:

表名:file_test

存储后的数据:

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>

运行效果:

上传文件:

选择文件:

提交成功后;

列表新增一条数据:

点击下载选择保存位置:

点击删除后:

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

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

      

完整素材及全部代码

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

https://download.csdn.net/download/xuezhe5212/89238404
 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/581969.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

《R语言与农业数据统计分析及建模》学习——回归分析

一、线性回归 线性回归是一种广泛用于数据分析、预测和建模的技术&#xff0c;可以帮助我们理解变量之间的关系&#xff0c;并进行预测和推断。 1、简单线性回归 简单线性回归是线性回归的一种特殊情况&#xff0c;适用于只有一个自变量和一个因变量的情况。 在R语言中&#x…

QT c++ 代码布局原则 简单例子

本文描述QT c widget代码布局遵循的原则&#xff1a;实中套虚&#xff0c;虚中套实。 本文最后列出了代码下载链接。 在QT6.2.4 msvc2019编译通过。 所谓实是实体组件&#xff1a;比如界面框、文本标签、组合框、文本框、按钮、表格、图片框等。 所谓虚是Layout组件&#x…

IT廉连看——UniApp——样式绑定

IT廉连看——UniApp——样式绑定 一、样式绑定 两种添加样式的方法&#xff1a; 1、第一种写法 写一个class属性&#xff0c;然后将css样式写在style中。 2、第二种写法 直接把style写在class后面 添加一些效果&#xff1a;字体大小 查看效果 证明这样添加样式是没有问题的…

WPF —— MVVM 指令执行不同的任务实例

标签页 设置两个按钮&#xff0c; <Button Content"修改状态" Width"100" Height"40" Background"red"Click"Button_Click"></Button><Button Content"测试"Width"100"Height"40&…

clickhous学习之旅二

接上回继续鼓捣clickhouse 1.常用数据类型 1.1整型 固定长度的整型&#xff0c;包括有符号整型或无符号整型。整型范围(-2n-1~2n-1-1): Int8 - [-128 :127] -->相当于java中的byte Int16-[-32768 :32767] -->相当于java中的short Int32-[-2147483648 :2147483647] -…

最新官方破解版会声会影2024永久序列号和激活码

会声会影2024是一款功能强大的视频编辑软件&#xff0c;它集合了视频剪辑、音频调整、特效添加等多项功能于一身&#xff0c;为用户提供了一个全面且易用的视频制作平台。无论是初学者还是专业视频编辑人员&#xff0c;都能在这款软件中找到满足自己创作需求的工具。 会声会影最…

基于残差神经网络的汉字识别系统+pyqt前段界面设计

研究内容: 中文汉字识别是一项具有挑战性的任务&#xff0c;涉及到对中文字符的准确分类。在这个项目中&#xff0c;目标是构建一个能够准确识别中文汉字的系统。这个任务涉及到数据集的收集、预处理、模型训练和评估等步骤。尝试了使用残差神经网络&#xff08;ResNet&#x…

windows电脑改造为linux

有个大学用的旧笔记本电脑没啥用了&#xff0c;决定把它改成linux搭一个服务器&#xff1b; 一、linux安装盘制作 首先要有一个大于8G的U盘&#xff0c;然后去下载需要的linux系统镜像&#xff0c;我下的是ubuntu&#xff0c;这里自选版本 https://cn.ubuntu.com/download/d…

中国移动旋转验证码的识别过程

一、前言 今天有空研究了一下这个移动的登录&#xff0c;发现获取手机验证码的时候会弹出一种旋转验证码。这种验证码确实挺头疼。所以顺便研究了一下如何识别。 验证码的样子大家先看一下。看看大家有没有什么更好是思路。 二、验证码识别 我这里就直接上代码。我这里是使用…

SpringMVC基础篇(四)

文章目录 1.视图1.基本介绍1.视图介绍2.为什么需要自定义视图 2.自定义视图实例1.思路分析2.代码实例1.view.jsp2.接口3.配置自定义视图解析器springDispatcherServlet-servlet.xml4.自定义视图MyView.java5.view_result.jsp6.结果展示 3.自定义视图执行流程4.自定义视图执行流…

web安全---xss漏洞/beef-xss基本使用

what xss漏洞----跨站脚本攻击&#xff08;Cross Site Scripting&#xff09;&#xff0c;攻击者在网页中注入恶意脚本代码&#xff0c;使受害者在浏览器中运行该脚本&#xff0c;从而达到攻击目的。 分类 反射型---最常见&#xff0c;最广泛 用户将带有恶意代码的url打开&a…

E-MapReduce极客挑战赛季军方案

前一段时间我参加了E-MapReduce极客挑战赛&#xff0c;很幸运的获得了季军。在这把我的比赛攻略给大家分享一下&#xff0c;希望可以抛砖引玉。 赛题分析与理解 赛题背景&#xff1a; 大数据时代&#xff0c;上云已成为越来越多终端客户大数据方案的落地选择&#xff0c;阿里…

Phi-3-mini-4k-instruct 的功能测试

Model card 介绍 Phi-3-Mini-4K-Instruct 是一个 3.8B 参数、轻量级、最先进的开放模型&#xff0c;使用 Phi-3 数据集进行训练&#xff0c;其中包括合成数据和经过过滤的公开可用网站数据&#xff0c;重点是 高品质和推理密集的属性。 该型号属于 Phi-3 系列&#xff0c;Mini…

Golang | Leetcode Golang题解之第58题最后一个单词的长度

题目&#xff1a; 题解&#xff1a; func lengthOfLastWord(s string) (ans int) {index : len(s) - 1for s[index] {index--}for index > 0 && s[index] ! {ansindex--}return }

虚拟机扩容-根目录挂载sda1的空间不足

提醒&#xff01;不管成不成功&#xff0c;一定要先备份一份虚拟机&#xff01;&#xff01;&#xff01;&#xff01;&#xff01; 走过路过点个关注吧&#xff0c;想到500粉丝&#xff0c;哭。一、查看分区情况 df -h可以看到/dev/sda1已经被占满了 2.关闭虚拟机&#xff…

windows驱动开发-WDF对象

WDF封装了大量的WDF对象&#xff0c;不过&#xff0c;和应用层不一样&#xff0c;不用去尝试从WDF框架对象类上派生和改写原有的WDF类&#xff0c;本意WDF就是希望我们使用这些对象和类&#xff0c;而不是创造新的奇怪的类。 每个WDF对象都代表着对一项驱动需要使用的子功能的…

vue学习的预备知识为学好vue打好基础

目录 Vue是什么 &#xff1f;如何使用Vue &#xff1f;Vue ApiVue入口apiVue实例apiVue函数api 无构建过程的渐进式增强静态HTMLVue模块化构建工具npmyarnWebpackvue-cliVite Vue是什么 &#xff1f; 文章基于Vue3叙述。 Vue (发音为 /vjuː/&#xff0c;类似 view) 是一款用于…

179. 最大数(LeetCode)

文章目录 前言一、题目讲解二、算法原理三、代码编写1.仿函数写法2.lambda表达式 四、验证五.总结 前言 在本篇文章中&#xff0c;我们将会带着大家采用贪心的方法解决LeetCode中最大数这道问题&#xff01;&#xff01;&#xff01; 一、题目讲解 一组非负整数&#xff0c;包…

【面试经典 150 | 图】被围绕的区域

文章目录 写在前面Tag题目来源解题思路方法一&#xff1a;深搜方法二&#xff1a;广搜 写在最后 写在前面 本专栏专注于分析与讲解【面试经典150】算法&#xff0c;两到三天更新一篇文章&#xff0c;欢迎催更…… 专栏内容以分析题目为主&#xff0c;并附带一些对于本题涉及到的…

03.Kafka 基本使用

Kafka 提供了一系列脚本用于命令行来操作 kafka。 1 Topic 操作 1.1 创建 Topic 创建一个名为 oldersix-topic 的 topic&#xff0c;副本数设置为3&#xff0c;分区数设置为2&#xff1a; bin/kafka-topics.sh \ --create \ --zookeeper 192.168.31.162:2181 \ --replication…