SpringBoot + thymeleaf 实现文件上传

1.目录结构

SpringBoot + thymeleaf 实现文件上传

2.upload.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>SpringBoot上传文件</title>
</head>
<body>
<h1>测试SpringBoot文件上传</h1>
<form th:action="@{/file/uploadByJarDeploy}" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit" value="上传文件">
</form>
</body>
</html>

3.FileController.java

package xin.baizhiedu.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class FileController {

    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @Value("${file.upload.dir}")
    private String realPath;

    /**
     * 第二种文件上传
     * 注意:这种方式适用于任何一种部署方式 推荐使用这种方式
     *
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("/uploadByJarDeploy")
    // 定义:接收文件对象 MultipartFile file变量名要与form表单中input type="file" 标签name属性名一致
    public String uploadByJarDeploy(MultipartFile file) throws IOException {

        // 文件名
        String originalFilename = file.getOriginalFilename();
        log.debug("文件名: {}", file.getOriginalFilename());
        log.debug("文件大小: {}", file.getSize());
        log.debug("文件类型: {}", file.getContentType());

        // 改文件名
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS-").format(new Date()) + UUID.randomUUID() + ext;

        // 上传文件到哪
        file.transferTo(new File(realPath, newFileName));
        return "redirect:/";
    }


    /**
     * 用来测试文件上传 - 这种方式:不能用于jar包部署
     * 注意:这种方式存在局限性, 不推荐再使用这种方式进行文件上传了
     *
     * @return
     */
    /*
    @RequestMapping("/uploadFile")
    // 定义:接收文件对象 MultipartFile file变量名要与form表单中input type="file" 标签name属性名一致
    public String uploadFileTest(MultipartFile file, HttpServletRequest request) throws IOException {

        // 文件名
        String originalFilename = file.getOriginalFilename();
        log.debug("文件名: {}", file.getOriginalFilename());
        log.debug("文件大小: {}", file.getSize());
        log.debug("文件类型: {}", file.getContentType());

        // 处理文件上传
        // 1.根据相对路径 "uploads" 获取绝对路径
        String realPath = request.getSession().getServletContext().getRealPath("/uploads");
        log.debug("获取的绝对路径: {}", realPath);

        // 2.上传文件  参数1:将文件写入到那个目录
        // 修改文件名

        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS-").format(new Date()) + UUID.randomUUID() + ext;
        file.transferTo(new File(realPath, newFileName));

        return "redirect:/";
    }
    */

}

4.application.yml

server:
  port: 8080
#  servlet:
#    context-path: /springboot-file

spring:
  servlet:
    multipart:   # # 修改文件上传的大小限制
      max-request-size: 1024MB   # 运行请求传递文件大小最大为1024MB
      max-file-size: 1024MB       # 运行服务器可以处理的最大文件大小1024MB
  profiles:
    active: local # 激活本地配置生效

logging:
  level:
    root: info
    xin.baizhiedu.controller: debug


# 指定文件上传位置
#file:
#  upload:
#    dir: D:\temp\1 # 指定本地测试上传目录

5.application-local.yml

# 指定文件上传位置
file:
  upload:
    dir: D:\temp\1 # 指定本地测试上传目录 (Windows系统)

6.application-prod.yml

# 指定文件上传位置
file:
  upload:
    dir: /home/user/uploads # 指定服务器测试上传目录(Linux系统)

7.pom.xml

<?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.5.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>xin.baizhiedu</groupId>
    <artifactId>springboot_day05-uploadFiles</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_day05-uploadFiles</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

8.测试

SpringBoot + thymeleaf 实现文件上传
SpringBoot + thymeleaf 实现文件上传
SpringBoot + thymeleaf 实现文件上传
SpringBoot + thymeleaf 实现文件上传
SpringBoot + thymeleaf 实现文件上传

上一篇:工作中的技术总结_ thymeleaf的应用 _select&input的数据回显 _20210910


下一篇:thymeleaf 只渲染文本,不需要html标签