目录
1、页面表单
1.1、前端代码:
单文件上传:<input type="file" name="headerImg" id="exampleInputFile">
多文件上传:<input type="file" name="photos" multiple>
表单提交:映射至"/upload"路径
<form role="form" th:action="@{/upload}" method="post" enctype="multipart/form-data">
<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="username">
</div>
<div class="form-group">
<label for="exampleInputFile">头像</label>
<!-- 单文件上传 id="exampleInputFile"-->
<input type="file" name="headerImg" id="exampleInputFile">
</div>
<div class="form-group">
<label for="exampleInputFile">生活照</label>
<!-- 多文件上传,使用multiple-->
<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>
1.2、页面效果
2、后端响应代码
2.1、进入表单页面
@GetMapping("/form_layouts")
public String form_layouts() {
return "form/form_layouts";
}
2.2、获取上传得到的文件并保存
2.2.1、获取表单提交的文件
利用@RequestParam("表单中的name"),获取提交的参数
利用@RequestPart("表单中的name"),获取提交的文件:
1)单文件:@RequestPart("headerImg") MultipartFile headerImg
2)多文件:@RequestPart("photos") MultipartFile[] photos
@PostMapping("/upload")
public String upload(@RequestParam("email") String email,
@RequestParam("username") String username,
//接收单文件
@RequestPart("headerImg") MultipartFile headerImg,
//接收多文件
@RequestPart("photos") MultipartFile[] photos)
throws IOException {}
2.2.2、获取的文件保存至服务器某路径中
步骤:
1)获取上传文件的名称:String originalFilename = headerImg.getOriginalFilename();
2)将文件保存至服务器:headerImg.transferTo(new File("D:\\photos\\" + originalFilename));
if (!headerImg.isEmpty()) {
//将上传的文件保存到服务器中
String originalFilename = headerImg.getOriginalFilename(); //获取文件原始名称
headerImg.transferTo(new File("D:\\photos\\" + originalFilename));
}
if (photos.length > 0) {
for (MultipartFile photo : photos) {
if (!photo.isEmpty()){
String originalFilename = photo.getOriginalFilename(); //获取文件原始名称
photo.transferTo(new File("D:\\photos\\" + originalFilename));
}
}
}
2.2.3、上传文件的大小限制
在配置文件中配置,上传文件的大小限制:
#单个文件的最大大小
spring.servlet.multipart.max-file-size=10MB
#整个请求文件的最大大小
spring.servlet.multipart.max-request-size=100MB
3、文件上传原理
文件上传自动配置类-MultipartAutoConfiguration-MultipartProperties
- 自动配置好了 StandardServletMultipartResolver 【文件上传解析器】
- 原理步骤:
1、请求进来使用文件上传解析器判断(isMultipart)并封装(resolveMultipart,返回
MultipartHttpServletRequest)文件上传请求
2、参数解析器来解析请求中的文件内容封装成MultipartFile
3、将request中文件信息封装为一个Map:
MultiValueMap<String,MultipartFile>FileCopyUtils,实现文件流的拷贝。