使用springboot2.0实现上传文件MultipartFile报空,找了一下午没有解决问题,最后思考是否是拦截器被拦截了,然后去掉拦截器配置,再次测试获取到了文件,确认拦截器问题后上网百度解决问题方法,今天早上找到解决办法:
添加配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
@Configuration
public class UploadConfig {
//显示声明CommonsMultipartResolver为mutipartResolver
@Bean(name = "multipartResolver")
public MultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("UTF-8");
//resolveLazily属性启用是为了推迟文件解析,以在在UploadAction中捕获文件大小异常
resolver.setResolveLazily(true);
resolver.setMaxInMemorySize(40960);
//上传文件大小 5M 5*1024*1024
resolver.setMaxUploadSize(5 * 1024 * 1024);
return resolver;
}
然后在springboot启动类中加入注解,排除原有的Multipart配置
//排除原有的Multipart配置
@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
如果遇到报错:java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory,原因是缺少依赖,加入以下依赖就好了:
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
原文中说道
Controller接收的时候一定要加上@RequestParam,否则不可用,如下所示:
@RequestParam("file") MultipartFile multipartFile
但是昨天做测试的时候,没有拦截器,不加@RequestParam()注解的话 才会进来参数,暂不知道是什么情况,目前的话,经过同事测试,springboot2.0还是加上吧先