如何实现文件上传?
前端文件上传表单代码:
<form role="form" th:action="@{/update}" 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="headerImg" id="exampleInputFile">
<p class="help-block">Example block-level help text here.</p>
</div>
<div class="form-group">
<label for="exampleInputFile">生活照</label>
<input type="file" 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">提交</button>
</form>
浏览器显示:
后端代码编写:
我们可以通过@RequestParam来获取上传来的文本字段,使用@RequestPart来获取上传的文件。
@PostMapping("/update")
public String upload(@RequestParam("email") String email,
@RequestParam("username") String username,
@RequestPart("headerImg") MultipartFile headerImg,
@RequestPart("photos") MultipartFile[] photos ) throws IOException {
//判断获取的文件是否为空
if(!headerImg.isEmpty()){
//文件不为空则获取文件名并存入磁盘
String filename = headerImg.getOriginalFilename();
headerImg.transferTo(new File("C:\\phototest\\"+filename));
}
//多文件上传
if(photos.length>0){
for (MultipartFile photo : photos) {
if(!photo.isEmpty()){
//文件不为空则获取文件名并存入磁盘
String originalFilename = photo.getOriginalFilename();
photo.transferTo(new File("C:\\phototest\\"+originalFilename));
}
}
}
return "main";
}
SpringBoot本身限制了文件上传的大小,我们还需要自定义上传文件的大小:
spring: servlet: multipart: max-file-size: 10MB max-request-size: 100MB
注意!一定要写清文件上传的磁盘路径(C:\\phototest\\),否则会报错!