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";
}
}
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>
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>

运行效果:

可以在 application.properties 中设置对上传文件大小进行限制的参数:
spring.servlet.multipart.max-request-size=100MB
spring.servlet.multipart.max-file-size=100MB
注意:由于 springboot 具有几个版本,不同版本对于文件上传最大限制的配置也有所不同。所以要注意 springboot 本身的版本,不然会一直报错
# 在springboot1.3版本中:
multipart.maxFileSize
# 在springboot1.4与springboot1.5版本中:
spring.http.multipart.max-file-size
# 在springboot2.0版本中:
spring.servlet.multipart.max-file-size
在 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>
方法二:
创建文件 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/");
}
}
修改 status.html 文件中的 单文件上传 模块的写法为:
<p>单文件上传p>
<p th:text="${msg}">p>
<div th:if="${msg == '文件上传成功!'}">
<img th:src="|upload/${src}|" width=10%>
<hr>

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