1. 先写一个html页面用来上传表单
我使用了一点thymeleaf,不了解无视即可。上传多文件和单文件都是用
file类型提交,多文件需要指定为multiple,接受时指定参数类型即可。
<!--upload.html-->
<!DOCTYPE html>
<html lang="en"xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form role="form" method="post" th:action="@{/upload}"
enctype="multipart/form-data">
email:<input type="email" name="email"><br>
name:<input type="text" name="name"><br>
<input type="file" name="file"><br>
<input type="file" name="files" multiple><br>
<input type="submit" value="提交">
</form>
</body>
</html>
2. 控制器处理请求
使用MultipartFile[]接受多文件类型,最后用增强for循环遍历写出,写出使用transferTo方法。
package com.yhr.boot04.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
public class upLoadController {
@GetMapping("/begin")
public String login(){
return "upload";
}
@PostMapping("/upload")
public void upload(@RequestParam("email") String email,
@RequestParam("name") String name,
@RequestPart("file") MultipartFile file,
@RequestPart("files") MultipartFile[] files) throws IOException {
System.out.println(email + "," + name);
if(!file.isEmpty()){
//文件名
String originalFilename = file.getOriginalFilename();
//springboot独特的写出操作,很方便
file.transferTo(new File("D:\\"+originalFilename));
}
if(files.length > 0){
//遍历文件
for (MultipartFile multipartFile : files) {
if(!multipartFile.isEmpty()){
String originalFilename = multipartFile.getOriginalFilename();
multipartFile.transferTo(new File("D:\\"+originalFilename));
}
}
}
}
}
3. 示例
按住shift选择两个文件

控制台打印email和name

成功将文件放入D盘中

4. 设置容量大小
如果报错提示:org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.
那么就可以在application.properties中设置文件大小
根据源码设置两个属性的值

#单个文件最大容量
spring.servlet.multipart.max-file-size=10MB
#多个文件最大容量
spring.servlet.multipart.max-request-size=100MB
本文介绍了如何在SpringBoot中实现多文件上传。首先创建一个HTML表单用于上传,然后在控制器中处理请求,接收多文件并保存到指定路径。同时,文章还提到如何设置文件上传的最大容量,以避免超出限制的错误。

2万+

被折叠的 条评论
为什么被折叠?



