1.问题描述:

之前用spring MVC,转成spring boot之后发现上传不能用。网上参考说是spring boot已经有CommonsMultipartResolver了,但是我的上传后台接收的还是null。

2.第一种解决方法

加入配置类

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配置
@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

 

 

第二种方法:注(请自行搜索您项目中Filter的拦截类,以下针对自己的项目中的请求)

如果说还是不行就可能项目中的file拦截器做了http请求处理或者做了请求转化,如果是因为这个下面解决方式重写方法

package com.wl.partner.aspect;
import com.cre.dmp.osp.app.gateway.RequestWrapper;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 此类为一个切面类,主要作用就是对接口的请求进行拦截
 * 注:废弃{拦截的方式,只需要在指定接口方法上面加上@MonitorRequest注解即可}
 * chufangbo
 * 2020-09-28
 */
@Aspect
@Component
@WebFilter(
        urlPatterns = {"*"},
        filterName = "tokenAuthorFilter"
)
public class RequestAspect implements Filter{
//    /**
//     * 表示在执行被@MonitorRequest 会执行doBefore()方法
//     *
//     * @param joinPoint 连接点,就是被拦截点
//     */
//    @Before(value = "@annotation(com.wl.partner.aspect.MonitorRequest)")
//    public void doBefore(JoinPoint joinPoint){
//        System.out.println("--------------表示在执行被@MonitorRequest 会执行doBefore()方法--------------------");
//            //获取到请求的属性
//        ServletRequestAttributes attributes =
//                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        //获取到请求对象
//        HttpServletRequest request = attributes.getRequest();
//        //URL:根据请求对象拿到访问的地址
//        urlGl=request.getRequestURL().toString();
//        logger.info("url=" + request.getRequestURL());
//        //获取请求的方法,是Get还是Post请求
//        logger.info("method=" + request.getMethod());
//        //ip:获取到访问
//        logger.info("ip=" + request.getRemoteAddr());
//        //获取被拦截的类名和方法名
//        logger.info("class=" + joinPoint.getSignature().getDeclaringTypeName() +
//                "and method name=" + joinPoint.getSignature().getName());
//        //参数
//        logger.info("参数=" + joinPoint.getArgs().toString());
//        //方法内部类即嵌套在方法里面
//    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest servletRequest1 = (HttpServletRequest) servletRequest;
        String requestURI = servletRequest1.getRequestURI();
        //TODO URL:根据请求对象拿到访问的地址(放开导入拦截) 此处需要配置项目路径的具体方法
//        List<String> passlist = new ArrayList<>();
//        passlist.add("/wl-ltx-partner-api/excelAllController/importCityManagerDealer");
//        passlist.add("/wl-ltx-partner-api/partnerController/importPartner");
        ServletRequest requestWrapper = null;
        if (!requestURI.contains("/wl-ltx-partner-api/excelAllController")) {
        //if (!passlist.contains(requestURI)) {
            requestWrapper = new RequestWrapper((HttpServletRequest)servletRequest);
        }
        if (requestWrapper == null) {
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>开始进入自定义导入:重写doFilter 跳过内置getWay拦截{HttpServletFilter}<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
            StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = new StandardMultipartHttpServletRequest((HttpServletRequest) servletRequest);
            filterChain.doFilter(standardMultipartHttpServletRequest, servletResponse);
        } else {
            //System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>走内置com.cre.dmp.osp.app.gateway.filter【getWay】拦截{HttpServletFilter}<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
            filterChain.doFilter(requestWrapper, servletResponse);
        }
    }
}

 

如果说还是不行请查询日志打印的请求拦截处理

跳过:&& !execution(* com.wl.partner.controller.ExcelAllController.*(..))  拦截

package com.wl.partner.aspect;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 全局日志打印--liuling
 */
@Component
@Aspect
@Slf4j
public class LogAspect {
    //跳过导入导出的controller&& !execution(* com.wl.partner.controller.ExcelAllController.*(..))
    @Pointcut("execution(public * com.wl.partner.controller..*.*(..)) && !execution(* com.wl.partner.controller.ExcelAllController.*(..))")
    public void webLog() {
    }
    
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        if (joinPoint.getArgs().length>0) {
            if (joinPoint.getArgs()[0] instanceof HttpServletResponse) {
                if (joinPoint.getArgs().length > 1) {
                    log.info("-------------------------------------收到请求 --> " + request.getRequestURL().toString() + ":" + JSONObject.toJSONString(joinPoint.getArgs()[1]));
                } else {
                    log.info("-------------------------------------收到请求 --> " + request.getRequestURL().toString());
                }
            } else {
                log.info("-------------------------------------收到请求 --> " + request.getRequestURL().toString() + ":" + JSONObject.toJSONString(joinPoint.getArgs()[0]));
            }

        }

    }
    
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求,返回内容
        log.info("-------------------------------------返回参数--> : " + JSONObject.toJSONString(ret));
    }
    
}