欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot文件上传与下载实战

程序员文章站 2022-06-02 14:10:05
...

一  pom

<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  http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>
     <groupId>org.fkit</groupId>
     <artifactId>fileuploadtest</artifactId>
     <version>0.0.1-SNAPSHOT</version>
     <packaging>jar</packaging>
     <name>fileuploadtest</name>
     <url>http://maven.apache.org</url>
     <!-- spring-boot-starter-parent是Spring Boot的核心启动器,  包含了自动配置、日志和YAML等大量默认的配置,大大简化了我们的开发。
           引入之后相关的starter引入就不需要添加version配置, spring  boot会自动选择最合适的版本进行添加。 -->
     <parent>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-parent</artifactId>
           <version>2.0.0.RELEASE</version>
           <relativePath />
     </parent>
     <properties>
           <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
           <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
           <java.version>1.8</java.version>
     </properties>
     <dependencies>
           <!-- 添加spring-boot-starter-web模块依赖 -->
           <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
           </dependency>
           <!-- 添加spring-boot-starter-thymeleaf模块依赖 -->
           <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
           </dependency>
           <!-- Apache Commons FileUpload组件依赖, 由于不属于Spirng Boot,所以需要加上版本 -->
           <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.3.3</version>
           </dependency>
           <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <scope>test</scope>
           </dependency>
     </dependencies>
</project>

二 启动类

package org.fkit.fileuploadtest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


//@SpringBootApplication指定这是一个 spring boot的应用程序.
@SpringBootApplication
public class App
{
    public static void main( String[] args )
    {
        // SpringApplication 用于从main方法启动Spring应用的类。
        SpringApplication.run(App.class, args);
    }
}

三 实体类

package org.fkit.fileuploadtest.domain;


import java.io.Serializable;
import org.springframework.web.multipart.MultipartFile;


public class User implements Serializable{
    
    private static final long serialVersionUID = 1L;
    
    private String username;
    // 对应上传的headPortrait,类型为MultipartFile,上传文件会自动绑定到image属性当中
    private MultipartFile headPortrait;
    
    public User() {
        super();
    }
    
    public String getUsername() {
        return username;
    }


    public void setUsername(String username) {
        this.username = username;
    }


    public MultipartFile getHeadPortrait() {
        return headPortrait;
    }
    public void setHeadPortrait(MultipartFile headPortrait) {
        this.headPortrait = headPortrait;
    }
}

四 控制器

package org.fkit.fileuploadtest.controller;


import java.io.File;
import java.net.URLEncoder;


import javax.servlet.http.HttpServletRequest;


import org.apache.commons.io.FileUtils;
import org.fkit.fileuploadtest.domain.User;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;


@Controller
public class FileUploadController {


    // 映射"/"请求
    @RequestMapping("/")
    public String index() {
        // 根据Thymeleaf默认模板,将返回resources/templates/index.html
        return "index";
    }


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


    // 上传文件会自动绑定到MultipartFile中
    @PostMapping(value = "/upload")
    public String upload(HttpServletRequest request, @RequestParam("description") String description,
            @RequestParam("file") MultipartFile file) throws Exception {
        // 接收参数description
        System.out.println("description = " + description);
        // 如果文件不为空,写入上传路径
        if (!file.isEmpty()) {
            // 上传文件路径
            String path = request.getServletContext().getRealPath("/upload/");
            System.out.println("path = " + path);
            // 上传文件名
            String filename = file.getOriginalFilename();
            File filepath = new File(path, filename);
            // 判断路径是否存在,如果不存在就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            // 将上传文件保存到一个目标文件当中
            file.transferTo(new File(path + File.separator + filename));
            return "success";
        } else {
            return "error";
        }
    }


    @RequestMapping(value = "/register")
    public String register(HttpServletRequest request, @ModelAttribute User user, Model model) throws Exception {
        // 接收参数username
        System.out.println("username = " + user.getUsername());
        // 如果文件不为空,写入上传路径
        if (!user.getHeadPortrait().isEmpty()) {
            // 上传文件路径
            String path = request.getServletContext().getRealPath("/upload/");
            System.out.println("path = " + path);
            // 上传文件名
            String filename = user.getHeadPortrait().getOriginalFilename();
            File filepath = new File(path, filename);
            // 判断路径是否存在,如果不存在就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            // 将上传文件保存到一个目标文件当中
            user.getHeadPortrait().transferTo(new File(path + File.separator + filename));
            // 将用户添加到model
            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.thymeleaf.cache=false
spring.http.multipart.maxFileSize=50MB
spring.http.multipart.maxRequestSize=50MB

六 模板

1 error.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">
     <!-- .panel-heading 面板头信息。 -->
     <div class="panel-heading">
           <!-- .panel-title 面板标题。 -->
           <h3 class="panel-title">文件上传下载示例</h3>
     </div>
</div>
<div class="col-md-8">
     <div class="alert alert-danger" role="alert">文件上传失败!</div>
</div>
</body>
</html>

2 index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<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">
     <!-- .panel-heading 面板头信息。 -->
     <div class="panel-heading">
           <!-- .panel-title 面板标题。 -->
           <h3 class="panel-title">文件上传下载示例:简单文件上传</h3>
     </div>
</div>
<div class="container">
     <div class="row">
           <div class="col-md-8">
                <form class="form-horizontal" action="upload"  enctype="multipart/form-data" method="post">
                     <div class="form-group">
                           <div class="input-group col-md-4">
                                <span  class="input-group-addon"><i class="glyphicon  glyphicon-pencil"></i></span>
                                <input class="form-control"  placeholder="文件描述" type="text" name="description" />
                           </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"  placeholder="请选择文件" type="file" name="file"/>
                           </div>
                     </div>
                     <div class="form-group">
                           <div class="col-md-4">
                                <div class="btn-group  btn-group-justified" >
                                       <div class="btn-group" >
                                         <button type="submit"  class="btn btn-success" id="submitbtn">
                                           <span  class="glyphicon glyphicon-share"></span>&nbsp;文件上传</button>
                                       </div>
                                </div>
                           </div>
                     </div>
                </form>
           </div>
     </div>
</div>
</body>
</html>

3 registerForm.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<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">
     <!-- .panel-heading 面板头信息。 -->
     <div class="panel-heading">
           <!-- .panel-title 面板标题。 -->
           <h3 class="panel-title">文件上传下载示例:用户注册</h3>
     </div>
</div>
<div class="container">
     <div class="row">
           <div class="col-md-8">
                <form class="form-horizontal" action="register"  enctype="multipart/form-data" method="post">
                     <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"  placeholder="用户名" 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"  placeholder="请选择头像" type="file" name="headPortrait"/>
                           </div>
                     </div>
                     <div class="form-group">
                           <div class="col-md-4">
                                <div class="btn-group  btn-group-justified" >
                                       <div class="btn-group" >
                                         <button type="submit"  class="btn btn-success" id="submitbtn">
                                           <span  class="glyphicon glyphicon-share"></span>&nbsp;注册</button>
                                       </div>
                                </div>
                           </div>
                     </div>
                </form>
           </div>
     </div>
</div>
</body>
</html>

4 success.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<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">
     <!-- .panel-heading 面板头信息。 -->
     <div class="panel-heading">
           <!-- .panel-title 面板标题。 -->
           <h3 class="panel-title">文件上传下载示例</h3>
     </div>
</div>
<div class="col-md-8">
     <div class="alert alert-success" role="alert">文件上传成功!</div>
</div>
</body>
</html>

5 userInfo.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<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">
     <!-- .panel-heading 面板头信息。 -->
     <div class="panel-heading">
           <!-- .panel-title 面板标题。 -->
           <h3 class="panel-title">文件上传下载示例:文件下载</h3>
     </div>
</div>
<div class="container">
           <div class="panel panel-primary">
                <!-- .panel-heading 面板头信息。 -->
                <div class="panel-heading">
                     <!-- .panel-title 面板标题。 -->
                     <h3 class="panel-title">用户信息列表</h3>
                </div>
                <div class="panel-body">
                     <div class="table table-responsive">
                           <table class="table table-bordered  table-hover" >
                                <tbody class="text-center">
                                     <tr>
                                           <td><img  th:src="@{'upload/'+${user.headPortrait.originalFilename}}"  height="30"/></td>
                                           <td  th:text="${user.username}">用户名</td>
                                           <td >
                                           <a  th:href="@{download(filename=${user.headPortrait.originalFilename })}">下载头像</a>
                                           </td>
                                     </tr>
                                </tbody>
                           </table>
                     </div>
                </div>
           </div>
     </div>
</body>
</html>

七 测试

Spring Boot文件上传与下载实战

Spring Boot文件上传与下载实战

Spring Boot文件上传与下载实战

Spring Boot文件上传与下载实战

Spring Boot文件上传与下载实战

相关标签: Spring Boot