SpringBoot-文件上传(单文件以及多文件上传)
在springboot中进行单文件以及多文件的上传
HTML代码
<form role="form" th:action="@{/upload}" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputFile">用户头像</label>
<input type="file" name="headerImg" id="exampleInputFile">
</div>
<div class="form-group">
<label for="exampleInputFile">生活照</label>
<input type="file" name="photos" multiple>
</div>
<button type="submit" class="btn btn-primary">提交</button>
</form>
Controller代码
/***
* MultipartFile自动封装上传过来的文件
* @param email
* @param username
* @param headerImg
* @param photos
* @return
*/
@PostMapping("/upload")
public String upload(
@RequestParam("headerImg") MultipartFile headerImg,
@RequestParam("photos") MultipartFile[] photos) throws IOException {
if(!headerImg.isEmpty()){
//保存到文件服务器 oss服务器
String originalFilename = headerImg.getOriginalFilename();
headerImg.transferTo(new File("E:\\Image\\"+originalFilename));
}
if (photos.length>0){
for (MultipartFile photo : photos) {
if (!photo.isEmpty()){
String originalFilename = photo.getOriginalFilename();
photo.transferTo(new File("E:\\Image\\"+originalFilename));
}
}
}
return "main";
}
上传示例图
Tips:
springboot的默认配置是单个上传不超过1MB,总体上传不超过10MB,如果选择文件过大则会抛异常
解决方案:在application.properties中进行自定义配置
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB