SpringBoot文件上传
1、页面表单
<form method="post" th:action="@{/upload}" enctype="multipart/form-data">
选择文件:<input value="" type="file" name="file">
<input value="" type="file" name="files" multiple>
<button id="search" type="submit">提交</button>
</form>
2、文件上传代码
@Controller
public class UpFileTestController {
@GetMapping("/upfile")
public String upFile(){
return "upfile/list";
}
@PostMapping("/upload")
public String upload(@RequestPart MultipartFile file,
@RequestPart MultipartFile[] files) throws IOException {
if (!file.isEmpty()){
String originalFilename = file.getOriginalFilename();
file.transferTo(new File("E:\\test\\"+originalFilename));
}
for(MultipartFile multipartFile : files){
if (!multipartFile.isEmpty()){
String originalFilename = System.currentTimeMillis()+multipartFile.getOriginalFilename();
multipartFile.transferTo(new File("E:\\test\\"+originalFilename));
}
}
return "redirect:/upfile";
}
}
自动配置原理
文件上传自动配置类-MultipartAutoConfiguration-MultipartProperties
自动配置好了 StandardServletMultipartResolver 【文件上传解析器】
原理步骤
1、请求进来使用文件上传解析器判断(isMultipart)并封装(resolveMultipart,返回MultipartHttpServletRequest)文件上传请求
2、参数解析器来解析请求中的文件内容封装成MultipartFile
3、将request中文件信息封装为一个Map;MultiValueMap<String, MultipartFile>
FileCopyUtils。实现文件流的拷贝
@PostMapping("/upload")
public String upload(@RequestParam("email") String email,
@RequestParam("username") String username,
@RequestPart("headerImg") MultipartFile headerImg,
@RequestPart("photos") MultipartFile[] photos)