基于SpringBoot实现SpringMvc上传下载功能实现

目录

SpringMvc上传下载功能实现

1.创建新的项目

1)项目信息填写

2)选择所用的包

3)创建controller包 

4)创建DownLoadController类

5)创建UpLoadController类

6)创建index.html

7)创建upload.html

2.实现上传功能

1)关键代码

2)详情解释

3)功能测试

3.文件下载功能实现

1)关键代码

2)详细解释

3)功能测试

​编辑

​编辑

​编辑        ​编辑       

4.附:

1)完整的DownLoadController 类代码

2)完整的UpLoadController 代码

                      


SpringMvc上传下载功能实现

1.创建新的项目

1)项目信息填写

  1. Spring Initializr (单击选中)
  2. Name(填写项目名字)
  3. Language(选择开发语言)
  4. Type(选择工具Maven)
  5. Group()
  6. JDK(jdk选择17 )
  7. Next(下一步)

2)选择所用的包

  1. Springboot (选择SpringBoot版本)
  2. 输入(web)
  3. 选择Spring Web
  4. 选择Thymeleaf
  5. create

3)创建controller包 

4)创建DownLoadController类

package com.xiji.springdemo01.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class DownLoadController {
   

    @RequestMapping("/")
    public String index(){
        return "index";
    }


}

5)创建UpLoadController类

package com.xiji.springdemo01.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 文件上传功能
 */
@Controller
public class UpLoadController {

    

    @RequestMapping("/up")
    public String uploadPage(){
        return "upload";
    }
}

在resources文件的static创建img文件夹===》导入图片

打开templates文件夹

6)创建index.html

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>精美主页面</title>
  <style>
    /* styles.css */
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f4f4f4;
    }

    header {
      background-color: #333;
      color: white;
      padding: 10px 0;
      text-align: center;
    }

    nav ul {
      list-style-type: none;
      padding: 0;
    }

    nav ul li {
      display: inline;
      margin-right: 10px;
    }

    nav ul li a {
      color: white;
      text-decoration: none;
    }

    main {
      padding: 20px;
      background-color: white;
      margin: 20px;
    }

    section {
      margin-bottom: 20px;
    }

    footer {
      background-color: #333;
      color: white;
      text-align: center;
      padding: 10px 0;
      position: fixed;
      width: 100%;
      bottom: 0;
    }

  </style>
</head>
<body>
<header>
  <nav>
    <ul>
      <li><a href="#home">首页</a></li>
      <li><a href="#services">服务</a></li>
      <li><a href="#about">关于我们</a></li>
      <li><a href="#contact">联系我们</a></li>
    </ul>
  </nav>
</header>
<main>


  <di style="width: 200px;height: 200px;">
    <a th:href="@{/download}">文件下载</a>
  </di>

</main>
<footer>
  <p>版权所有 © 2023 我们的公司</p>
</footer>
</body>
</html>



注:<a th:href="@{/download}">文件下载</a> 这个路径对应的是后端的下载接口

7)创建upload.html

<!DOCTYPE html>
<html lang="zh-CN" >
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>文件上传</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
  <style>
    body {
      font-family: 'Arial', sans-serif;
      background-color: #f4f4f9;
      margin: 0;
      padding: 0;
    }
    .container {
      max-width: 600px;
      margin: 50px auto;
      padding: 20px;
      background-color: #fff;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }
    h1 {
      text-align: center;
      color: #333;
    }
    .form-group {
      margin-bottom: 20px;
    }
    .btn-primary {
      width: 100%;
    }
    .custom-file-input ~ .custom-file-label {
      background-color: #e9ecef;
      border-color: #ced4da;
    }
    .custom-file-input:focus ~ .custom-file-label {
      border-color: #80bdff;
      box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
    }
  </style>
</head>
<body>
<div class="container">
  <h1>文件上传</h1>
  <form id="uploadForm" method="post" action="http://127.0.0.1:8080/upload" enctype="multipart/form-data">
    <div class="form-group">
      <label for="fileInput">选择文件:</label>
      <input type="file" class="form-control-file" id="fileInput" name="fileInput">
    </div>
    <button type="submit" class="btn btn-primary">上传文件</button>
  </form>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>

</script>
</body>
</html>j

注:<input type="file" class="form-control-file" id="fileInput" name="fileInput">

                                                                                        name值与接口值一致

解释

  1. form 元素创建了一个表单,其属性包括:
    1.  id 设置为 "uploadForm",可以在JavaScript中引用此表单。
    2. method 设置为 "post",表示数据将通过POST方法提交到服务器。
    3. action 指定了接收上传文件的服务器端脚本地址。
    4. enctype 设置为 "multipart/form-data",这是必须的,因为它允许表单发送二进制文件数据(如图片或文档)。       
  2. input 类型为 "file",允许用户从本地文件系统选择一个或多个文件进行上传。
  3. 最后,一个带有类 "btn btn-primary" 的按钮用于提交表单。

2.实现上传功能

1)关键代码

/**
 * 通过MultipartFile实现上传
 */
@RequestMapping("/upload")
@ResponseBody
public String upload(MultipartFile fileInput) throws IOException {


    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

    //获取上传文件夹的路径资源
    Resource resource = resolver.getResource("classpath:static/img/");
    //获取文件夹真实路径
    String path = resource.getFile().getPath();
    //路径拼接
    String filePath = path + File.separator + fileInput.getOriginalFilename();
    //通过transferTo()方法返回给前端
    fileInput.transferTo(new File(filePath));
    return "上传成功";

}

2)详情解释

  • 注解说明:
    •  @RequestMapping("/upload"): 定义了处理 HTTP 请求的 URL 映射。
    • @ResponseBody: 表示该方法返回的内容将直接作为 HTTP 响应体返回给客户端。
  • 接收上传文件:
    • MultipartFile fileInput: 用于接收上传的文件。
  • 获取文件夹路径:
    • PathMatchingResourcePatternResolver resolver: 用于解析文件资源路径。
    • resolver.getResource("classpath:static/img/"): 获取指定路径下的文件夹资源。
    • String path = resource.getFile().getPath();: 获取文件夹的真实路径。
  • 拼接文件路径:
    • String filePath = path + File.separator + fileInput.getOriginalFilename();: 拼接完整的文件路径。
  • 保存文件:
    • fileInput.transferTo(new File(filePath));: 将上传的文件保存到指定路径。
  • 返回结果:
    • return "上传成功";: 返回上传成功的消息。

3)功能测试

打开 http://127.0.0.1:8080/up

http://127.0.0.1:8080/up

任选一张图片

打开idea ===> target ==> classes ===> static ==> img ==>看到已经成功上传到服务器

可以看到已经上传成功了

       

3.文件下载功能实现

1)关键代码

/**
 *
 * 通过PathMatchingResourcePatternResolver + ResponseEntity 下载文件
 */
@RequestMapping("/download")
@ResponseBody
public ResponseEntity<byte[]> download() throws IOException {
    //获取文件地址
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource resource = resolver.getResource("static/img/1.png");
                                ​​​​​​​        ​​​​​​​        // 1.png修改为你导入的图片名称
    //获取文件
    File file = resource.getFile();


    //获取文件流
    FileInputStream fileInputStream = new FileInputStream(file);
    //创建每次读取的字节数为文件本身大小
    byte[] bytes = new byte[fileInputStream.available()];
    //相当于把文件流 输入到  bytes 字节数组中
    fileInputStream.read(bytes);

    //设置下载方式
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("Content-Disposition", "attachment; filename=" + file.getName());
    //状态码设置
    HttpStatus ok = HttpStatus.OK;

   //创建ResponseEntity返回给前端

    ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, ok);


    return responseEntity;
}

2)详细解释

  • 注解说明:
    •  @RequestMapping("/download"): 定义了处理 HTTP 请求的 URL 映射。
    • @ResponseBody: 表示该方法返回的内容将直接作为 HTTP 响应体返回给客户端。
  • 文件资源解析:
    • PathMatchingResourcePatternResolver: 用于解析文件资源路径。
    •  getResource("static/img/1.png"): 获取指定路径下的文件资源。
  • 文件对象获取:
    • File file = resource.getFile();: 将资源转换为 File 对象。
  • 设置响应头:
    •  HttpHeaders httpHeaders: 创建响应头对象。
    •  httpHeaders.add("Content-Disposition", "attachment; filename=" + file.getName()): 设置响应头,指定文件以附件形式下载,并设置文件名。
  • 状态码设置:
    • HttpStatus ok = HttpStatus.OK: 设置 HTTP 状态码为 200 OK。
  • 读取文件内容:
    •  FileInputStream fileInputStream = new FileInputStream(file);: 创建文件输入流。
    • byte[] bytes = new byte[fileInputStream.available()];: 创建字节数组。
    •  fileInputStream.read(bytes);: 读取文件内容到字节数组中。
  • 创建响应实体:
    •  ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, ok);:
    • 创建 ResponseEntity 对象,包含文件内容、响应头和状态码。
  • 返回响应:
    • return responseEntity;: 返回响应实体。

3)功能测试

打开网址 打开网址打开网址  http://127.0.0.1:8080/打开网址 



        
       

可以看到我们已经下载成功了

4.附:

1)完整的DownLoadController 类代码

package com.xiji.springdemo01.controller;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Controller
public class DownLoadController {
    /**
     *
     * 通过PathMatchingResourcePatternResolver + ResponseEntity 下载文件
     */
    @RequestMapping("/download")
    @ResponseBody
    public ResponseEntity<byte[]> download() throws IOException {
        //获取文件地址
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource resource = resolver.getResource("static/img/1.png");

        //获取文件
        File file = resource.getFile();


        //获取文件流
        FileInputStream fileInputStream = new FileInputStream(file);
        //创建每次读取的字节数为文件本身大小
        byte[] bytes = new byte[fileInputStream.available()];
        //相当于把文件流 输入到  bytes 字节数组中
        fileInputStream.read(bytes);

        //设置下载方式
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Disposition", "attachment; filename=" + file.getName());
        //状态码设置
        HttpStatus ok = HttpStatus.OK;


        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, ok);


        return responseEntity;
    }



    @RequestMapping("/")
    public String index(){
        return "index";
    }


}

2)完整的UpLoadController 代码

package com.xiji.springdemo01.controller;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 文件上传功能
 */
@Controller
public class UpLoadController {

    /**
     * 通过MultipartFile实现上传
     */
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile fileInput) throws IOException {


        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        Resource resource = resolver.getResource("classpath:static/img/");

        String path = resource.getFile().getPath();
        //路径拼接
        String filePath = path + File.separator + fileInput.getOriginalFilename();
        fileInput.transferTo(new File(filePath));
        return "上传成功";

    }

    @RequestMapping("/up")
    public String uploadPage(){
        return "upload";
    }
}



        

       
       



        

       
        
       

                

        

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

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

相关文章

dubbo三

dubbo dubbo架构各层说明 URL举例解析 消费者引用服务过程 项目初始化

nginx服务介绍

nginx 安装使用配置静态web服务器 Nginx是一个高性能的Web服务器和反向代理服务器&#xff0c;它最初是为了处理大量并发连接而设计的。Nginx还可以用作负载均衡器、邮件代理服务器和HTTP缓存。它以其轻量级、稳定性和高吞吐量而闻名&#xff0c;广泛用于大型网站和应用中 Ngin…

SpringCloud Feign 以及 一个标准的微服务的制作

一个标准的微服务制作 以一个咖啡小程序项目的订单模块为例&#xff0c;这个模块必将包括&#xff1a; 各种实体类&#xff08;pojo,dto,vo....&#xff09; 控制器 controller 服务类service ...... 其中控制器中有的接口需要提供给其他微服务&#xff0c;订单模块也需要…

55.【C语言】字符函数和字符串函数(strstr函数)

11.strstr函数 *简单使用 strstr: string string cplusplus的介绍 点我跳转 翻译: 函数 strstr const char * strstr ( const char * str1, const char * str2 ); 或另一个版本char * strstr ( char * str1, const char * str2 ); 寻找子字符串 返回指向第一次出现在字…

软件测试 | APP测试 —— Appium 的环境搭建及工具安装教程

大家应该都有同一种感觉&#xff0c;学习appium最大的难处之一在于环境的安装&#xff0c;安装流程比较繁琐&#xff0c;安装的工具和步骤也较多&#xff0c;以下是基于Windows系统下的Android手机端的安装流程。就像我们在用Selenium进行web自动化测试的时候一样&#xff0c;我…

计算机的错误计算(九十六)

摘要 探讨 的计算精度问题。 计算机的错误计算&#xff08;五十五&#xff09;与&#xff08;七十八&#xff09;分别列出了 IEEE 754-2019 中的一些函数与运算。下面再截图给出其另外3个运算。 例1. 已知 x-0.9999999999966 . 计算 不妨在Python下计算&#xff0c;则有&am…

phpstudy 建站使用 php8版本打开 phpMyAdmin后台出现网页提示致命错误:(phpMyAdmin这是版本问题导致的)

报错提示&#xff1a; 解决方法&#xff1a;官网下载phpmyadmin 5.2.1版本。 下载地址&#xff1a;phpMyAdmin 将网站根目录phpMyAdmin4.8.5里面的文件换成 官网下载的5.2.1版本即可。 重启网站&#xff0c;打开phpMyAdmin后台即可&#xff08;若打不开更改 mysql密码即可&am…

【有啥问啥】弱监督学习新突破:格灵深瞳多标签聚类辨别(Multi-Label Clustering and Discrimination, MLCD)方法

弱监督学习新突破&#xff1a;格灵深瞳多标签聚类辨别&#xff08;Multi-Label Clustering and Discrimination, MLCD&#xff09;方法 引言 在视觉大模型领域&#xff0c;如何有效利用海量无标签图像数据是一个亟待解决的问题。传统的深度学习模型依赖大量人工标注数据&…

rabbitmq容器化部署

需求 容器化部署rabbitmq服务 部署服务 找到如下官网信息版本 官网版本发布信息 这里看到最新版本是3.13版本&#xff0c;这里在3.13中找一个版本下载容器镜像即可。 找到dockrhub.com中 找到3.13.2版本镜像。 容器服务安装此处省略 现在下载容器镜像需要配置容器代理 ~#…

树莓派提示:error: externally-managed-environment 树莓派安装虚拟环境,树莓派flask报错

错误信息 raspberryraspberrypi:~ $ pip install flask error: externally-managed-environment脳 This environment is externally managed 鈺扳攢> To install Python packages system-wide, try apt install python3-xyz, where xyz is the package you are trying to i…

进程间关系与进程守护

一、进程组 1、理解 每一个进程除了有一个进程 ID(PID)之外 还属于一个进程组&#xff0c; 进程组是一个或者多个进程的集合&#xff0c; 一个进程组可以包含多个进程。 每一个进程组也有一个唯一的进程组 ID(PGID)&#xff0c; 并且这个 PGID 类似于进程 ID&#xff0c; 同样…

微信电脑版聊天图片DAT格式文件转为普通JPG图片

1-7 本文章主要教你如何恢复微信聊天中的聊天图片&#xff0c;主要应用场景是&#xff0c;当你的微信被封号了&#xff0c;或者无法登录了&#xff0c;会导致微信聊天中的聊天图片没办法再打开&#xff0c;如果是重要的图片&#xff0c;那就有损失了&#xff0c;所以有了本文的…

android 删除系统原有的debug.keystore,系统运行的时候,重新生成新的debug.keystore,来完成App的运行。

1、先上一个图&#xff1a;这个是keystore无效的原因 之前在安装这个旧版本android studio的时候呢&#xff0c;安装过一版最新的android studio&#xff0c;然后通过模拟器跑过测试的demo。 2、运行旧的项目到模拟器的时候&#xff0c;就报错了&#xff1a; Execution failed…

Fisco Bcos 2.11.0配置console控制台2.10.0及部署调用智能合约

Fisco Bcos 2.11.0配置console控制台2.10.0及部署调用智能合约 文章目录 Fisco Bcos 2.11.0配置console控制台2.10.0及部署调用智能合约前言版本适配一、启动FIsco Bcos区块链网络二、获取控制台文件三、配置控制台3.1 执行download_console.sh脚本3.2 拷贝控制台配置文件3.3 修…

react crash course 2024 (1)理论概念

state的作用 react hooks 而无需写一个class jsx 样式用 spa

WebGL系列教程六(纹理映射与立方体贴图)

目录 1 前言2 思考题3 纹理映射介绍4 怎么映射&#xff1f;5 开始绘制5.1 声明顶点着色器和片元着色器5.2 修改顶点的颜色为纹理坐标5.3 指定顶点位置和纹理坐标的值5.4 获取图片成功后进行绘制5.5 效果5.6 完整代码 6 总结 1 前言 上一讲我们讲了如何使用索引绘制彩色立方体&a…

TDengine 首席架构师肖波演讲整理:探索新型电力系统的五大关键场景与挑战

在 7 月 26 日的 TDengine 用户大会上&#xff0c;涛思数据&#xff08;TDengine&#xff09;首席架构师肖波进行了题为《TDengine 助力新型电力系统高质量发展》的主题演讲。他不仅分享了 TDengine 在新型电力系统中的应用案例&#xff0c;还深入探讨了如何利用 TDengine 的高…

构建响应式API:FastAPI Webhooks如何改变你的应用程序

FastAPI&#xff0c;作为一个现代、快速&#xff08;高性能&#xff09;的Web框架&#xff0c;为Python开发者提供了构建API的卓越工具。特别是&#xff0c;它的app.webhooks.post装饰器为处理实时Webhooks提供了一种简洁而强大的方法。在本文中&#xff0c;我们将探讨如何使用…

后端开发刷题 | 打家劫舍

描述 你是一个经验丰富的小偷&#xff0c;准备偷沿街的一排房间&#xff0c;每个房间都存有一定的现金&#xff0c;为了防止被发现&#xff0c;你不能偷相邻的两家&#xff0c;即&#xff0c;如果偷了第一家&#xff0c;就不能再偷第二家&#xff1b;如果偷了第二家&#xff0…

new/delete和malloc/free到底有什么区别

new和malloc 文章目录 new和malloc前言一、属性上的区别二、使用上的区别三、内存位置的区别四、返回类型的区别五、分配失败的区别六、扩张内存的区别七、系统调度过程的区别总结 前言 new和malloc的知识点&#xff0c;作为一个嵌入式工程师是必须要了解清楚的。new和malloc的…