一、使用方法
HTML ——
指定type类型为 file type="file"
若是一次性上次多个文件,后面加上 multiple
<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>
Controller ——
1. 取得用户上传的文件
使用 @RequestPart("前端定义的文件名") MultipartFile 前端定义的文件名
取得用户上次的文件
若是接收多个文件,则使用 MultipartFile[]
数组形式接收
2. 将接收到的文件上传到某个位置
通过 MultipartFile
提供的 transferTo
方法 (要注意判断文件是否为空)
示例代码:
@Slf4j
@Controller
public class FormTestController {
@GetMapping("/form_layouts")
public String from_layouts(){
return "form/form_layouts";
}
@PostMapping("/upload")
public String upload(@RequestParam("email") String email, @RequestParam("username") String username,
@RequestPart("headerImg") MultipartFile headerImg,
@RequestPart("photos") MultipartFile[] photos) throws IOException {
log.info("上传文件的信息: email={}, username={}, headerImg={}, photos={}", email, username, headerImg.getSize(), photos.length);
if(!headerImg.isEmpty()){
// 保存到文件服务器,OSS 服务器
String originalFilename = headerImg.getOriginalFilename();
// 将文件传输到某个地方
headerImg.transferTo(new File("D:\\" + originalFilename));
if(photos.length > 0){
for (MultipartFile photo : photos){
if(photo.isEmpty()){
headerImg.transferTo(new File("D:\\" + photo));
}
}
}
}
return "main";
}
}
二、解决文件大小超过最大长度问题
原理——
SpringBoot关于文件参数的信息被定义在 MultipartProperties.class 中,通过进入 MultipartProperties.class 查看,可以观察到单个文件上传的大小不能超过 1MB 并且总请求上传的文件大小和不能超过 10MB。
通过查看 MultipartAutoConfiguration.class ,可以找到对文件参数进行修改的方式为通过配置 spring.servlet.multipart
调整固定参数,具体操作如下:
解决方式——
在 application.properties 文件中加入如下代码:
spring.servlet.multipart.max-file-size=10MB #将最大文件大小改为 10MB
spring.servlet.multipart.max-request-size=100MB #将总大小改为100MB