【笔记】SpringBoot项目实现文件上传

前言

SpringBoot项目实现文件上传

单文件上传

1
2
3
4
<form action="http://127.0.0.1:8080/file" method="post" enctype="multipart/form-data">
<input name="fileImage" type="file" />
<input type="submit" value="提交"/>
</form>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@RequestMapping("/file")
public void file(@RequestParam("file") MultipartFile file) throws IOException {
// 获取文件名
String filename = file.getOriginalFilename();
// 定义文件存放路径
File dir = new File("");
if (!dir.exists()) {
dir.mkdirs();
}
// 创建File对象
File fileObj = new File(dir + "/" + filename);
// 上传到指定目录
file.transferTo(fileObj);
}

多文件上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RequestMapping("/file")
public void fileUpload(MultipartFile[] fileList) throws IOException {
for (MultipartFile file : fileList) {
// 获取文件名
String filename = file.getOriginalFilename();
// 定义文件存放路径
File dir = new File("");
if (!dir.exists()) {
dir.mkdirs();
}
// 创建File对象
File fileObj = new File(dir + "/" + filename);
// 上传到指定目录
file.transferTo(fileObj);
}
}

配置文件上传大小

  • SpringBoot文件上传超出范围会报错:The field fileImage exceeds its maximum permitted size of 1048576 bytes.

SpringBoot1.4之后

  • 如果不想设限制,则值设置为-1

maxFileSize:配置单个文件大小
maxRequestSize:配置所有文件总大小(请求总大小)

1
2
spring.http.multipart.maxFileSize=10Mb
spring.http.multipart.maxRequestSize=100Mb

SpringBoot2.0之后

  • 如果不想设限制,则值设置为-1

max-file-size:配置单个文件大小
multipart.max-request-size:配置所有文件总大小(请求总大小)

1
2
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB

完成

参考文献

CSDN——FaceToBook
CSDN——我是蚁人