Spring Boot实现文件上传下载

 更新时间:2022年08月14日 14:47:38   作者:云淡风轻58  
这篇文章主要为大家详细介绍了Spring Boot实现文件上传下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了Spring Boot实现文件上传下载的具体代码,供大家参考,具体内容如下

示例【Spring Boot  文件上传下载】

程序清单:/springboot2/src/main/resources/templates/register.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>注册</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}" >
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" />
<script type="text/javascript" th:src="@{js/jquery-1.11.0.min.js}"></script>
<script type="text/javascript" th:src="@{js/bootstrap.min.js}"></script>
</head>
<body>
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">Spring Boot文件上传</h3>
        </div>
    </div>
    <div class="container">
        <div class="row">
            <div class="col-md-8">
                <form action="upload" method="post" enctype="multipart/form-data">
                    <div class="form-group">
                        <div class="input-group col-md-4">
                            <span class="input-group-addon">
                                <i class="glyphicon glyphicon-user"></i>
                            </span>
                            <input class="form-control" type="text" name="userName">
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="input-group col-md-4">
                            <span class="input-group-addon">
                                <i class="glyphicon glyphicon-search"></i>
                            </span>
                            <input class="form-control" type="file" name="head">
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-md-4">
                            <button type="submit" class="btn btn-success">注册</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

程序清单:/springboot2/src/main/resources/templates/userInfo.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户信息</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}" >
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" />
<script type="text/javascript" th:src="@{js/jquery-1.11.0.min.js}"></script>
<script type="text/javascript" th:src="@{js/bootstrap.min.js}"></script>
</head>
<body>
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">Spring Boot文件下载</h3>
        </div>
    </div>
    <div class="container">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <h3 class="panel-title">用户信息列表</h3>
            </div>
        </div>
        <div class="panel-body">
            <div class="table table-responsive">
                <table class="table table-bordered" id="userTable">
                    <tbody class="text-center">
                        <tr>
                            <td><img th:src="@{'upload/'+${user.head.originalFilename}}" height="30"></td>
                            <td th:text="${user.userName}">用户名</td>
                            <td><a th:href="@{download(filename=${user.head.originalFilename })}" >下载</a></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>

程序清单:/springboot2/src/main/java/com/dwx/hello/User.java

package com.dwx.hello;
import org.springframework.web.multipart.MultipartFile;
public class User {
    private String userName;
    private MultipartFile head;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public MultipartFile getHead() {
        return head;
    }
    public void setHead(MultipartFile head) {
        this.head = head;
    }
}

程序清单:/springboot2/src/main/java/com/dwx/hello/UserController.java

package com.dwx.hello;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.ResponseEntity.BodyBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class UserController {
    @RequestMapping("/registerForm")
    public String registerForm() {
        return "register";
    }
    @RequestMapping("/upload")
    public String upload(HttpServletRequest request,
            @ModelAttribute User user,Model model) throws IllegalStateException, IOException {
        if(!user.getHead().isEmpty()) {
            String path=request.getServletContext().getRealPath("/upload");
            String fileName=user.getHead().getOriginalFilename();
            File filePath=new File(path,fileName);
            if(!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            user.getHead().transferTo(new File(path+File.separator+fileName));
            model.addAttribute("user", user);
            return "userInfo";
        }else {
            return "error";
        }
    }
    @RequestMapping(value="/download")
     public ResponseEntity<byte[]> download(HttpServletRequest request,
             @RequestParam("filename") String filename,
             @RequestHeader("User-Agent") String userAgent,
             Model model)throws Exception{
        // 下载文件路径
        String path = request.getServletContext().getRealPath(
               "/upload/");
        // 构建File
        File file = new File(path+File.separator+ filename);
        // ok表示Http协议中的状态 200
       BodyBuilder builder = ResponseEntity.ok();
       // 内容长度
       builder.contentLength(file.length());
       // application/octet-stream : 二进制流数据(最常见的文件下载)。
       builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
       // 使用URLDecoder.decode对文件名进行解码
       filename = URLEncoder.encode(filename, "UTF-8");
       // 设置实际的响应文件名,告诉浏览器文件要用于【下载】、【保存】attachment 以附件形式
       // 不同的浏览器,处理方式不同,要根据浏览器版本进行区别判断
       if (userAgent.indexOf("MSIE") > 0) {
               // 如果是IE,只需要用UTF-8字符集进行URL编码即可
               builder.header("Content-Disposition", "attachment; filename=" + filename);
       } else {
               // 而FireFox、Chrome等浏览器,则需要说明编码的字符集
               // 注意filename后面有个*号,在UTF-8后面有两个单引号!
               builder.header("Content-Disposition", "attachment; filename*=UTF-8''" + filename);
       }
       return builder.body(FileUtils.readFileToByteArray(file));
     }
}

运行Spring Boot项目,访问以下地址:http://localhost:8080/registerForm

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Java Array.sort()源码分析讲解

    Java Array.sort()源码分析讲解

    Arrays类中有一个sort()方法,该方法是Arrays类的静态方法,在需要对数组进行排序时,非常的好用。但是sort()的参数有好几种,下面我就为大家一一介绍,这几种形式的用法
    2022-08-08
  • Mybatisplus如何存储List、Map

    Mybatisplus如何存储List、Map

    这篇文章主要介绍了Mybatisplus如何存储List、Map问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-01-01
  • SpringBoot动态定时任务实现完整版

    SpringBoot动态定时任务实现完整版

    最近有幸要开发个动态定时任务,这里简单再梳理一下,下面这篇文章主要给大家介绍了关于SpringBoot动态定时任务实现的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-02-02
  • java数据类型与变量的安全性介绍

    java数据类型与变量的安全性介绍

    这篇文章主要介绍了java数据类型与变量的安全性介绍,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下
    2022-07-07
  • JSON.toJSONString()空字段不忽略修改的问题

    JSON.toJSONString()空字段不忽略修改的问题

    这篇文章主要介绍了JSON.toJSONString()空字段不忽略修改的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-02-02
  • SpringBoot整合Liquibase的示例代码

    SpringBoot整合Liquibase的示例代码

    本篇文章给大家介绍SpringBoot整合Liquibase的两种情况分析,看似整合问题很简单,但是很容易出错,下面小编给大家介绍下整合步骤,感兴趣的朋友跟随小编一起看看吧
    2022-02-02
  • java 排序算法之冒泡排序

    java 排序算法之冒泡排序

    这篇文章主要介绍了java 排序算法之冒泡排序,文中运用大量的代码讲解相关知识,非常详细,感兴趣的小伙伴可以参考一下
    2021-09-09
  • SpringBoot使用Sharding-JDBC实现数据分片和读写分离的方法

    SpringBoot使用Sharding-JDBC实现数据分片和读写分离的方法

    本文主要介绍了SpringBoot使用Sharding-JDBC实现数据分片和读写分离,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-10-10
  • 一篇文章带你了解mybatis的动态SQL

    一篇文章带你了解mybatis的动态SQL

    这篇文章主要为大家介绍了mybatis的动态SQL ,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-01-01
  • 将字符串数字格式化为样式1,000,000,000的方法

    将字符串数字格式化为样式1,000,000,000的方法

    这篇文章主要介绍了将字符串数字格式化为样式1,000,000,000的方法,有需要的朋友可以参考一下
    2014-01-01

最新评论