需要注意的几个点:
- 文件名重名,防止覆盖(文中样例没有实现)
- 上传文件类型限定(文中样例没有实现)
- 写入权限判断或异常处理(文中样例没有实现)
表单
<form role="form" th:action="@{/upload}" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputEmail1">邮箱</label>
<input type="email" class="form-control" name="email" id="exampleInputEmail1"
placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">姓名</label>
<input type="text" class="form-control" name="username" id="exampleInputPassword1"
placeholder="姓名">
</div>
<div class="form-group">
<label for="exampleInputHeaderImg">头像</label>
<input type="file" name="headerImg" id="exampleInputHeaderImg">
<p class="help-block">请选择一个图片作为头像</p>
</div>
<div class="form-group">
<label for="exampleInputPhotos">相册</label>
<input type="file" name="photos" id="exampleInputPhotos" multiple>
<p class="help-block">请选择多个图片作为相册</p>
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Check me out
</label>
</div>
<button type="submit" class="btn btn-primary">提交</button>
</form>
控制器
@PostMapping(path = "/upload")
public String upload(@RequestParam("email") String email,
@RequestParam("username") String username,
@RequestParam("headerImg") MultipartFile headerImg,
@RequestParam("photos") MultipartFile[] photos) throws IOException {
log.info("上传的信息:email={}, username={}, headerImg={}, photos={}",
email, username, headerImg.getSize(), photos.length);
// 文件重命名
// 保存到文件服务器,OSS服务器,或本地磁盘
if (!headerImg.isEmpty()) {
// 获取文件名
String originalFileName = headerImg.getOriginalFilename();
// 写入目标路径
headerImg.transferTo(new File("D:\\upload\\" + originalFileName));
}
if (photos.length > 0) {
for (MultipartFile photo : photos) {
if (!photo.isEmpty()) {
// 获取文件名
String originalFileName = photo.getOriginalFilename();
// 写入目标路径
photo.transferTo(new File("D:\\upload\\" + originalFileName));
}
}
}
return "index.html";
}
上传文件大小限制
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 100MB