使用SpringBoot进行简单的文件上传

本文将介绍如何在 Spring Boot
中进行最基本的文件上传操作。
文件上传
如果要将上传文件解析为 MultipartFile 对象,通常需要使用文件解析器。在 Spring Boot 中,默认使用的是 StandardServletMultipartResolver
,它会自动解析文件上传请求并将文件转换为 MultipartFile 对象。
1 | public class MultipartAutoConfiguration { |
创建文件上传表单
在前端页面中创建一个表单,允许用户选择并上传图片文件。使用
<input type="file">
标签来实现文件上传。1
2
3
4
5
6<!-- 注意enctype必须为 multipart/form-data
-->
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" >
<input type="submit" value="Upload">
</form>后端处理文件上传
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
public class FileUploadController {
public ResponseData handleFileUpload( { MultipartFile file)
//判空
if (image.isEmpty()) {
// TODO 文件为空处理
}
//将文件存放到服务器
//1.获取原始文件名
String originalFilename = image.getOriginalFilename();
//2.创建新文件
File file = new File("yourpath/" + originalFilename);
//3.将MultipartFile对象转换为文件
try {
image.transferTo(file);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}请替换
"yourpath/"
为你希望存储上传文件的实际目录。上传相关配置
可按照需求配置。
1
2
3
4
5
6
7
8
9
10
11
12##文件上传配置
spring:
servlet:
multipart:
#开启MultipartResolver,默认为true
enabled: true
##设置文件上传位置
location: classpath:images/
#限制文件大小
max-file-size: 5MB
#限制整个请求的大小
max-request-size: 10MB
- 本文标题:使用SpringBoot进行简单的文件上传
- 创建时间:2023-10-31 21:43:55
- 本文链接:2023/10/31/java/使用SpringBoot进行简单的文件上传/
- 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
评论