springboot+thymeleaf 文件上传功能的实现代码

 更新时间:2020年11月25日 14:31:34   作者:weize_hh  
这篇文章主要介绍了springboot+thymeleaf 文件上传功能的实现代码,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

pom.xml

<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>

application.yml

spring:
 servlet:
  multipart:
   #上传文件总的最大值
   max-request-size: 10MB
   #上传文件的最大值
   max-file-size: 10MB

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>
    <p><span th:text="${msg}"></span></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>

hello.html 上传成功的页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</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>

controller:  文件上传

import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
 
 
@Controller
public class FileUploadController {
 
  //单一文件上传
  @RequestMapping("/upload")
  public String uploadFile(@RequestParam("file00") MultipartFile file, Model model){
    String msg="";
    try {
      if(file.isEmpty()){
        model.addAttribute("msg","上传失败,请选择文件!");
        return "index";
      }
      String filename = file.getOriginalFilename();
      //String filePath = request.getServletContext().getRealPath("/upload");
      String filePath = ResourceUtils.getURL("classpath:").getPath()+"static/";
 
      //避免文件重复覆盖
      String uuid= UUID.randomUUID().toString().replaceAll("-", "");
      //时间戳分类文件
      String time = new SimpleDateFormat("YYYY-MM").format(new Date());
 
      String realPath = filePath+time+"/"+uuid+filename;
      File dest = new File(realPath);
      //检测是否存在目录,无,则创建
      if(!dest.getParentFile().exists()){
        dest.getParentFile().mkdirs();//新建文件夹 多级目录
      }
 
      file.transferTo(dest);//文件写入
 
    } catch (IOException e) {
      e.printStackTrace();
    }
    model.addAttribute("msg","文件上传成功!");
    return "hello";
 
  }
 
  //多文件上传
  @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 "hello";
  }
 
}

测试:

文件上传文件上传2文件上传3

注:目前仅实现了文件的上传

计划补充:文件下载+上传的图片展示;

上传的图片展示:

遇到的问题:  直接使用 realPath 作为图片拼接地址  浏览器报 安全错误

notallow

使用字符串拼接,也会报错404

index = realPath.lastIndexOf("static");
upFilePaths.add("../"+realPath.substring(index));

到此这篇关于springboot+thymeleaf 文件上传功能的实现代码的文章就介绍到这了,更多相关springboot thymeleaf 文件上传内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 详解Java正则表达式中Pattern类和Matcher类

    详解Java正则表达式中Pattern类和Matcher类

    java.util.regex是一个用正则表达式所订制的模式来对字符串进行匹配工作的类库包。包括两个类Pattern和Matcher Pattern,Pattern是一个正则表达式经编译后的表现模式。Matcher对象是一个状态机器,它依据Pattern对象做为匹配模式对字符串展开匹配检查。
    2016-12-12
  • 如何使用NSSM将jar包打成Windows服务

    如何使用NSSM将jar包打成Windows服务

    这篇文章主要介绍了如何使用NSSM将jar包打成Windows服务,本文通过图文并茂的形式给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
    2024-03-03
  • 使用mybatis报Invalid bound statement解决分析

    使用mybatis报Invalid bound statement解决分析

    这篇文章主要为大家介绍了使用mybatis报Invalid bound statement原因解决分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • Java有趣好玩的图形界面开发八个案例实现

    Java有趣好玩的图形界面开发八个案例实现

    今天使用GUI技术写了几个练习的Demo,希望对大家学习图形用户界面有所帮助,感兴趣的同学来看看吧,动手敲一遍理解更通透
    2022-05-05
  • 关于Springboot | @RequestBody 接收到的参数对象属性为空的问题

    关于Springboot | @RequestBody 接收到的参数对象属性为空的问题

    这篇文章主要介绍了关于Springboot | @RequestBody 接收到的参数对象属性为空的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-03-03
  • JDBC获取元数据demo

    JDBC获取元数据demo

    这篇文章主要为大家介绍了JDBC获取元数据实现示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-11-11
  • SpringBoot MyBatis保姆级整合教程

    SpringBoot MyBatis保姆级整合教程

    因为Spring Boot框架开发的便利性,所以实现Spring Boot与数据访问层框架(例如MyBatis)的整合非常简单,主要是引入对应的依赖启动器,并进行数据库相关参数设置即可
    2022-06-06
  • idea 实现搜索jdk中的类和包操作

    idea 实现搜索jdk中的类和包操作

    这篇文章主要介绍了idea 实现搜索jdk中的类和包操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • 关于@Value取值为NULL的解决方案

    关于@Value取值为NULL的解决方案

    这篇文章主要介绍了关于@Value取值为NULL的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-07-07
  • Springboot中使用拦截器、过滤器、监听器的流程分析

    Springboot中使用拦截器、过滤器、监听器的流程分析

    Javaweb三大组件:servlet、Filter(过滤器)、 Listener(监听器),这篇文章主要介绍了Springboot中使用拦截器、过滤器、监听器的流程分析,感兴趣的朋友跟随小编一起看看吧
    2023-12-12

最新评论