一、使用
1、构建文件上传表单
2、文件上传代码
//表单提交必须用post请求
@PostMapping("/upload")
public String upload(@RequestParam("email") String email,
@RequestParam("username") String username,
@RequestPart("headerImg") MultipartFile headerImg, // MultipartFile:用于上传文件功能 @RequestPart:获取表单里的文件项
@RequestPart("photos") MultipartFile[] photos) throws IOException {
log.info("上传的信息:email={},username={},headerImg={},photos={}",
email,username,headerImg.getSize(),photos.length);
if(!headerImg.isEmpty()){ //isEmpty,getOriginalFilename,transferTo:都是MultipartFile接口里的方法
String originalFilename = headerImg.getOriginalFilename();
headerImg.transferTo(new File("D:\\cache\\"+originalFilename));//transferTo:文件保存(传输)到哪
}
if(photos.length>0){
for (MultipartFile photo : photos) {
if(!photo.isEmpty()){
String originalFilename = photo.getOriginalFilename();
photo.transferTo(new File("D:\\cache\\"+originalFilename));
}
}
}
return "main";
}
}
如果上传出现了超出限制的大小异常
org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException: The field profile-photo exceeds its maximum permitted size of 1048576 bytes.
可以修改底层默认限制文件的大小:
spring.servlet.multipart.max-file-size=10 #单个文件最大的大小
#多文件上传时,总的一次提交的最大大小,默认是10MB,改成100
spring.servlet.multipart.max-request-size=100
二、原理
文件上传自动配置类是MultipartAutoConfiguration,MultipartProperties所有有关文件上传的配置都封装在MultipartProperties里
springboot已经自动配置好了StandardServletMultipartResolver【文件上传解析器】它只能解析标准的以servlet的方式,相当于以servlet协议上传过来的文件。如果是自定义方式,直接往上传流的方式应该写自定义的文件上传解析器
@Configuration( proxyBeanMethods = false ) @ConditionalOnClass({Servlet.class, StandardServletMultipartResolver.class, MultipartConfigElement.class}) @ConditionalOnProperty( prefix = "spring.servlet.multipart", name = {"enabled"}, matchIfMissing = true ) @ConditionalOnWebApplication( type = Type.SERVLET ) @EnableConfigurationProperties({MultipartProperties.class}) public class MultipartAutoConfiguration { private final MultipartProperties multipartProperties; public MultipartAutoConfiguration(MultipartProperties multipartProperties) { this.multipartProperties = multipartProperties; } @Bean @ConditionalOnMissingBean({MultipartConfigElement.class, CommonsMultipartResolver.class}) public MultipartConfigElement multipartConfigElement() { return this.multipartProperties.createMultipartConfig(); } @Bean( name = {"multipartResolver"} ) @ConditionalOnMissingBean({MultipartResolver.class}) public StandardServletMultipartResolver multipartResolver() { StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver(); multipartResolver.setResolveLazily(this.multipartProperties.isResolveLazily()); return multipartResolver; } }