MultipartFile
。即用MultipartFile
来接收文件,只需几行代码即可实现<div class="form-group">
<!--单文件-->
<label for="headImage">选择头像</label>
<input type="file" id="headImage" name="headImage">
<p class="help-block">Example block-level help text here.</p>
</div>
<!--多文件-->
<div class="form-group">
<label for="photos">生活照</label>
<input type="file" id="photos" name="photos" multiple>
<p class="help-block">Example block-level help text here.</p>
</div>
+ 单文件判断是否为空 调用isEmpty()方法
+ 多文件判断长度是否大于0,获得单个文件后,继续判断是否为空
method="post" enctype="multipart/form-data
固定写死<form role="form" th:action="@{/load_files}" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputEmail1">电子邮件</label>
<input type="email" name="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">姓名</label>
<input type="text" name="username" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="form-group">
<label for="headImage">选择头像</label>
<input type="file" id="headImage" name="headImage">
<p class="help-block">Example block-level help text here.</p>
</div>
<div class="form-group">
<label for="photos">生活照</label>
<input type="file" id="photos" name="photos" multiple>
<p class="help-block">Example block-level help text here.</p>
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Check me out
</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
@SneakyThrows
@PostMapping("/load_files")
public String load(@RequestParam("email") String email,
@RequestParam("username") String username,
@RequestPart("headImage") MultipartFile headImg,
@RequestPart("photos") MultipartFile[] photos){
if (!headImg.isEmpty()){
// 获取文件名字
String name = headImg.getOriginalFilename();
// 不为空,保存 路径必须存在,不存在会报错
headImg.transferTo(new File("e://cache//"+name));
}
if (photos.length > 0){
for (MultipartFile photo : photos) {
if (photo.isEmpty()){
continue;
}
String name = photo.getOriginalFilename();
photo.transferTo(new File("e://cache//photos//"+name));
}
}
log.info("上传成功");
return "main";
}
spring:
servlet:
multipart:
max-file-size: 10MB #单个文件大小
max-request-size: 100MB #所有文件大小
原文:https://www.cnblogs.com/yangxiao-/p/14245806.html