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 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);
        //设置单个上传数据总大小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
posted @ 2020-03-11 15:14  zendwang  阅读(6657)  评论(1编辑  收藏  举报