1,页面表单

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
<form role="form" th:action="@{/upload}" method="post" enctype="multipart/form-data">  <!-- 书写enctype表示此表单为文件上传表单 -->

<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" name="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
</div>

<div class="form-group">
<label for="exampleUsername">姓名</label>
<input type="text" name="username" class="form-control" id="exampleUsername" placeholder="username">
</div>

<div class="form-group">
<label for="exampleInputFile">头像</label>
<input type="file" name="headerImg" id="exampleInputFile"> <!-- 此时为单文件上传 -->
</div>

<div class="form-group">
<label for="exampleInputPhotos">生活照</label>
<input type="file" name="photos" id="exampleInputPhotos" multiple> <!-- 加上multiple后,此时为多文件上传 -->
</div>

<button type="submit" class="btn btn-primary">Submit</button>
</form>


2,文件上传代码(将前台传过来的文件保存在服务器本地)

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
26
// MultipartFile 自动封装上传过来的文件
@PostMapping("/upload")
public String upLoad(@RequestParam("email") String email,
@RequestParam("username") String username,
@RequestPart("headerImg") MultipartFile headerImg, // 使用 @RequestPart 对文件类型注解
@RequestPart("photos") MultipartFile[] photos) throws IOException {
/* 注意在application.properties中配置最大上传文件大小,避免上传失败 */
log.info("上传的信息:email={}, username={}. headerImg={}, photos={}",
email, username, headerImg.getSize(), photos.length);
// 如果文件不为空
if(!headerImg.isEmpty()){
// 保存到文件服务器,OSS服务器
String originalFilename = headerImg.getOriginalFilename();// 原始的文件名
headerImg.transferTo(new File("D:\\RenComp\\ehcache\\upload\\"+originalFilename)); // 利用transferTo将文件保存在对应路径
}
if (photos.length > 0){
// 遍历文件,对所有文件进行保存
for (MultipartFile photo : photos) {
if (!photo.isEmpty()){
String originalFilename = photo.getOriginalFilename();
photo.transferTo(new File("D:\\RenComp\\ehcache\\upload\\"+originalFilename));
}
}
}
return "redirect:/index.html"; // 从post需要重定向到index.html 否则会因为地址栏的/upload报错不支持GET方式请求
}