【笔记】SpringBoot实现文件上传

前言

SpringBoot项目实现文件上传

前端页面

1
2
3
4
<form action="http://localhost/file" method="post" enctype="multipart/form-data">
<input name="fileImage" type="file" />
<input type="submit" value="提交"/>
</form>

SpringMVC做处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@RequestMapping("/file")
public null 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);
}

完成