springboot+thymeleaf 文件上传功能的实现代码
作者:weize_hh 发布时间:2023-11-25 05:08:59
标签: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";
}
}
测试:
注:目前仅实现了文件的上传
计划补充:文件下载+上传的图片展示;
上传的图片展示:
遇到的问题: 直接使用 realPath 作为图片拼接地址 浏览器报 安全错误
使用字符串拼接,也会报错404
index = realPath.lastIndexOf("static");
upFilePaths.add("../"+realPath.substring(index));
来源:https://blog.csdn.net/weize_hh/article/details/110118814


猜你喜欢
- 下面是一段大家都比较熟悉的代码:Handler handler = new Handler(); handler.post(myThread
- 1.导入pom依赖<!-- mybatis-->  
- .net内存回收与Dispose﹐Close﹐Finalize方法一. net的对象使用一般分为三种情况﹕1.创建对象2.使用对象3.释放对
- 什么是AOPAOP是 Aspect Oriented Programming 的缩写,即面向切面编程,和平常遇到的面向对象OOP编程不一样的
- 反射允许我们在编译期或运行时获取程序集的元数据,通过反射可以做到:● 创建类型的实例● 触发方法● 获取属性、字段信息● 延迟绑定.....
- Windows 服务(即,以前的 NT 服务)使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序。这些服务可以在计
- 话不多说,请看代码/// <summary>/// 删除字符串中的中文/// </summary>public st
- Spring Cloud Feign简介 Spring Cloud Feign也是一个基础工具类,它整合了Spring Cloud Ribb
- final可以修饰类 ,成员变量,局部变量和方法。1.final修饰成员变量1.final成员变量的初始化对于final修饰的变量,系统不会
- 下载:DownLoaderTask.javapackage com.johnny.testzipanddownload;import jav
- Collectors.toMap空指针问题在工作中遇到了一个List转Map的时候的一个NullPointException.情形很简单,问
- 前言自己android开发也有些年头了,每每回想起作为初学者的时候自己写的代码,自己会有种喷自己的冲动,代码写的太渣了。因此想着自己要总结下
- Java Hutool 包工具类推荐 ExcelUtil包引入hutool包版本号可根据实际情况更换<dependency> &
- 前言:在日常的Android开发中会经常和控件打交道,有时Android提供的控件未必能满足业务的需求,这个时候就需要我们实现自定义一些控件
- 先看下效果:两种需求场景:1.广告页3s后跳转到首页2.短信验证码60s倒计时第一种的话,根据需求我们可以知道,我们想要的效果就是3s结束做
- Android系统对所有的危险权限进行了分组,称为 权限组 。属于同一组的危险权限将自动合并授予,用户授予应用某个权限组的权限,则应用将获得
- 在 App 的开发过程中,ListView 控件是比较常用的控件之一。掌握它的用法,能帮助我们在一定程度上提高开发效率。本文将会介绍 Lis
- 一、简介CyclicBarrier 字面意思回环栅栏(循环屏障),它可以实现让一组线程等待至某个状态(屏障点)之后再全部同时执行。叫做回环是
- C和指针相关基础知识:内存的分配(谭浩强版)1、整型变量的地址与浮点型/字符型变量的地址区别?(整型变量/浮点型变量的区别是什么)2、int
- 在日常开发中,可能会遇到同一份代码,需要根据运营需求打出不同包名、不同图标、不同名称的Apk,发布到不同的渠道中。Android Studi