- 表单页面
<form role="form" th:action="@{/upload}" 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="exampleInputFile">头像</label>
<input type="file" name="headImage" id="exampleInputFile">
</div>
<div class="form-group">
<label for="exampleInputFile">生活照</label>
<input type="file" name="photos" multiple >
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Check me out
</label>
</div>
<button type="submit" class="btn btn-primary">提交</button>
</form>
其中, <input type="file" name="photos" multiple >
中multipart
属性是设置其为多文件上传。
2. 文件上传代码
@PostMapping("/upload")
public String upload(@RequestParam("email") String email,
@RequestParam("username")String username,
@RequestPart("headImage") MultipartFile headImage,
@RequestPart("photos") MultipartFile[] photos) throws IOException {
log.info("email={},username={},headImage={},photos={}",email,username,headImage.getSize(),photos.length);
if(!headImage.isEmpty()){
headImage.transferTo(new File("D:\\1\\"+headImage.getOriginalFilename()));
}
if(photos.length>0){
for(MultipartFile photo:photos){
photo.transferTo(new File("D:\\1\\"+photo.getOriginalFilename()));
}
}
return "main";
}
- 以上代码运行可能会报如下错误。这是因为上传的文件大笑超过了设定的大小。
解决方法:
文件上传自动配置类是:MultipartAutoConfigration,该自动配置类绑定了MultipartProperties.class属性。
所以我们需要在配置文件中application.properties中重新设置文件上传的大小限制。如下所示。
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB
重新运行即可。