文件上传
前端页面form表单
<!-- 文件上传功能form表单需要加上 enctype="multipart/form-data" -->
<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标签需要加上 mutiple -->
<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>
后端接口Controller
@Controller
public class FormController{
@PostMapping("/upload")
public String upload(@RequestPart MultipartFile oneImage,
@RequestPart("photos") MultipartFile[] moreImage)throws IOException{
//以下处理也可以通过service层进行处理
if(!oneImage.isEmpy()){
//这里可以上传到文件服务器
//拿到文件名
String fileName = oneImage.getOriginalFilename();
//传输到哪个位置 展示放到本地
oneImage.transferTo(new File("D:\\image\\"));
}
if(moreImage.length>0){
for(MultipartFile photo: moreImage){
String fileName = photo.getOriginalFileName();
photo.thansferTo(new File("D:\\image\\"));
}
}
}
}