SpringBoot上传⽂件时MultipartFile报空问题解决⽅法
1.问题描述
spring boot上传不能⽤,上传后台接收的还是null。总是报各种错误例如:Required request part 'file' is not present,Current request is not a multipart request.
SpringBoot默认是基于StandardServletMultipartResolve处理,MultipartStandardServletMultipartResolver依赖于Servlet3.0对multipart请求的⽀持(始于Spring3.1);CommonsMultipartResolver使⽤Jakarta Commons FileUpload解析multipart请求。本⽂最终采⽤CommonsMultipartResolver。
2.解决办法
2.1 加⼊配置类
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipartmons.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);
//设置了⽂件放⼊临时⽂件夹的最⼩⼤⼩限制
springframework依赖
resolver.setMaxInMemorySize(40960);
//设置单个上传数据总⼤⼩25M
resolver.setMaxUploadSizePerFile(25*1024*1024);
//设置总上传数据总⼤⼩50M
resolver.setMaxUploadSize(5 * 1024 * 1024);
return resolver;
}
}
2.2 在springboot启动类上加⼊注解
//排除原有的Multipart配置
@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
特别注意Controller接收的时候⼀定要加上@RequestParam,否则不可⽤,如下所⽰:
@RequestParam("file") MultipartFile multipartFile
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论