• Thymeleaf小功能总结


    一、Thymeleaf 文件上传

      FileUploadController.java:

    package com.hui.demo.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.ui.ModelMap;
    import org.springframework.util.ResourceUtils;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.MultipartRequest;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.UUID;
    
    @Controller
    public class FileUploadController {
    
        // 单一文件上传
        @RequestMapping("/upload")
        // @RequestParam 参数可去掉
        public String uploadFile(@RequestParam("file00") MultipartFile file, Model model){
            if(file.isEmpty()){
                model.addAttribute("msg","上传失败,请选择文件!");
            } else {
                try {
                    String filename = file.getOriginalFilename();
                    // 第一种存放的位置为D:/WorkSpace/Idea/SpringbootTest4/target/classes/static/
    //            String filePath = ResourceUtils.getURL("classpath:").getPath()+"static/";
                    // 第二种存放的位置为D://huiq/
                    String filePath = "d://huiq/";
    
                    //避免文件重复覆盖
                    String uuid= UUID.randomUUID().toString().replaceAll("-", "");
                    //时间戳分类文件
                    String time =  new SimpleDateFormat("YYYY-MM").format(new Date());
    
                    String realPath = filePath+time+"/"+uuid+filename;
                    System.out.println("realPath-->"+realPath);
                    File dest = new File(realPath);
                    //检测是否存在目录,无,则创建
                    if(!dest.getParentFile().exists()){
                        dest.getParentFile().mkdirs();//新建文件夹 多级目录
                    }
    
                    // 文件写入第一种方式
    //            file.transferTo(dest);
    
                    // 文件写入第二种方式
    //            Path path= Paths.get(realPath.substring(1,realPath.length())); // 使用第一种存放位置的时候
                    Path path= Paths.get(realPath); // 使用第二种存放位置的时候
                    Files.write(path,file.getBytes());
    
                    model.addAttribute("msg","文件上传成功!");
                } catch (IOException e) {
                    e.printStackTrace();
                    model.addAttribute("msg","文件上传失败!");
                }
            }
            return "thymeleaf/status";
        }
    
        //多文件上传
        @RequestMapping("/batch")
        public String uploadMoreFiles(HttpServletRequest request, Model model){
            MultipartRequest request1 = (MultipartRequest)request;
            //猜测 file为 input 类型为 file
            List<MultipartFile> fileList = request1.getFiles("file");
            List<String> msgList = new ArrayList<>();
            System.out.println(fileList.size());
            try {
                String filepath = ResourceUtils.getURL("classpath:").getPath()+"static/";
                for (int i=1;i<=fileList.size();i++){
                    MultipartFile file = fileList.get(i-1);
                    if (file.isEmpty()){
                        msgList.add("上传第"+i+"个文件失败");
                        model.addAttribute("msgList",msgList);
                        continue;
                    }
                    String filename = file.getOriginalFilename();
                    //避免文件重复覆盖
                    String uuid= UUID.randomUUID().toString().replaceAll("-", "");
                    //时间戳分类文件
                    String time =  new SimpleDateFormat("YYYY-MM").format(new Date());
    
                    String realPath = filepath+time+"s/"+uuid+filename;
                    File dest = new File(realPath);
                    //System.out.println("realPath"+realPath);
                    //检测是否存在目录,无,则创建
                    if(!dest.getParentFile().exists()){
                        dest.getParentFile().mkdirs();//新建文件夹 多级目录
                    }
                    msgList.add("第"+i+"个文件,上传成功!");
                    file.transferTo(dest);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            model.addAttribute("msgList",msgList);
            return "thymeleaf/status";
        }
    
        @RequestMapping("/index")
        public String index(ModelMap map){
            return "thymeleaf/index";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119

      index.html:

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>文件上传title>
    head>
    <body>
    <p>单文件上传p>
    <form method="post" action="/upload" enctype="multipart/form-data">
        <p><input type="file" name="file00">p>
        <input type="submit" value="提交">
    form>
    
    <hr/>
    <p>多文件上传p>
    <form method="post" enctype="multipart/form-data" action="/batch">
        <p>文件1:<input type="file" name="file"/>p>
        <p>文件2:<input type="file" name="file"/>p>
        <p><input type="submit" value="上传"/>p>
    form>
    
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

      status.html:

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
    head>
    <body>
    
    <p>单文件上传p>
    <p th:text="${msg}">p>
    <hr>
    <p>多文件上传p>
    <ul>
        <li th:each="msg1:${msgList}" th:text="${msg1}">li>
    ul>
    
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    在这里插入图片描述
      运行效果:

    在这里插入图片描述
      可以在 application.properties 中设置对上传文件大小进行限制的参数:

    spring.servlet.multipart.max-request-size=100MB
    spring.servlet.multipart.max-file-size=100MB
    
    • 1
    • 2
    • max-file-size:指定上传文件允许的最大大小。 默认值为1MB
    • max-request-size:指定 multipart/form-data 请求允许的最大大小。 默认值为10MB。

    注意:由于 springboot 具有几个版本,不同版本对于文件上传最大限制的配置也有所不同。所以要注意 springboot 本身的版本,不然会一直报错

    # 在springboot1.3版本中:
    multipart.maxFileSize
    
    # 在springboot1.4与springboot1.5版本中:
    spring.http.multipart.max-file-size
    
    # 在springboot2.0版本中:
    spring.servlet.multipart.max-file-size
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    1. 上传之后对图片进行预览

      在 FileUploadController.java 文件的 uploadFile 方法中增加一行代码:model.addAttribute("src",time+"/"+uuid+filename);

    方法一:
      在 application.properties 中增加一行配置:spring.resources.static-locations=file:D:/huiq/

      修改 status.html 文件中的 单文件上传 模块为:

    <p>单文件上传p>
    <p th:text="${msg}">p>
    <div th:if="${msg == '文件上传成功!'}">
        <img th:src="@{${src}}" width=10%>
        
        
    <hr>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    方法二:
      创建文件 TextThymeleaf.java

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    class TextThymeleaf implements WebMvcConfigurer {
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry){
            registry.addResourceHandler("/upload/**").addResourceLocations("file:D:/huiq/");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

      修改 status.html 文件中的 单文件上传 模块的写法为:

    <p>单文件上传p>
    <p th:text="${msg}">p>
    <div th:if="${msg == '文件上传成功!'}">
         <img th:src="|upload/${src}|" width=10%>
    <hr>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在这里插入图片描述

    2. 上传之后弹窗

      在 FileUploadController.java 文件的 uploadFile 方法中修改返回值为:return "thymeleaf/index";

      修改 index.html 文件中的 单文件上传 模块为:

    <p>单文件上传p>
    <form method="post" action="/upload" enctype="multipart/form-data">
        <p><input type="file" name="file00">p>
        <input type="submit" value="提交">
    form>
    <div th:if="${msg == '文件上传成功!'}">
        <script>
            alert("文件上传成功!")
        script>
    div>
    <div th:if="${msg == '上传失败,请选择文件!'}">
        <script>
            alert("上传失败,请选择文件!")
        script>
    div>
    <div th:if="${msg == '文件上传失败!'}">
        <script>
            alert("文件上传失败!")
        script>
    div>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    在这里插入图片描述

  • 相关阅读:
    简述什么是服务端包含(Server Side Include)?
    MongoDB学习二:基本常用命令--增删改查
    UML 类图
    2022年编程语言排名,官方数据来了,让人大开眼界
    qt qml
    【白话spring cloud(一)】为什么要用spring cloud?
    1921. 消灭怪物的最大数量
    Beego 使用教程 6:Web 输入处理
    Pytest测试框架搭建的关键6个知识点(建议收藏)
    【2014NOIP普及组】T4:子矩阵 试题解析
  • 原文地址:https://blog.csdn.net/m0_37739193/article/details/127591154