Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

spring boot - Required MultipartFile parameter 'file' is not present

I am using Spring Boot to test a upload functionality, and getting 'Required MultipartFile parameter 'file' is not present' error. Following are the 1) JSP, 2) Controller 3) Config Class 4) embedded tomcat log.

  1. JSP page

    ----------------------------------------------------------------------------
    <!DOCTYPE html>
    
    <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    
    <html lang="en">
    
    <body>
        <br>Message: ${message}
        <h2>List Of Objects</h2>
    
        <br>
        <h2>Upload New File to this Bucket</h2>
        <form action="uploadObject" method="post" enctype="multipart/form-data">
            <table width="60%" border="1" cellspacing="0">
                <tr>
                    <td width="35%"><strong>File to upload</strong></td>
                    <td width="65%"><input type="file" name="file" /></td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td><input type="submit" name="submit" value="Add" /></td>
                </tr>
            </table>
        </form>
    </body>
    </html>
    

2. Controller:

@RequestMapping(value = "/uploadObject", method = RequestMethod.POST)
    @Override
    public String upload(@RequestParam("file") MultipartFile file,
            @RequestParam("bucketName") String bucketName,
            Map<String, Object> model) {

        LOG.info("Object name parameter is " + file.getOriginalFilename());
        LOG.info("Bucket name parameter is " + bucketName);
....
}

3) Config Class:

package com.phi.piranha.client.config;

import javax.servlet.MultipartConfigElement;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.embedded.MultiPartConfigFactory;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Configuration
@EnableAutoConfiguration
@ComponentScan("com.phi.piranha")
public class PiranhaStorageServiceClientApplication extends
        SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(
            final SpringApplicationBuilder application) {
        return application
                .sources(PiranhaStorageServiceClientApplication.class);
    }

    @SuppressWarnings("PMD.SignatureDeclareThrowsException")
    public static void main(final String[] args) throws Exception {
        SpringApplication.run(PiranhaStorageServiceClientApplication.class,
                args);
    }

    @Bean
    MultipartConfigElement multipartConfigElement() {
        MultiPartConfigFactory factory = new MultiPartConfigFactory();
        factory.setMaxFileSize("1024KB");
        factory.setMaxRequestSize("1024KB");
        return factory.createMultipartConfig();
    }

    @Bean
    CommonsMultipartResolver multipartResolver(){
        return new CommonsMultipartResolver();
    }
}

4) Emedded Tomcat log:

  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _    
( ( )\___ | '_ | '_| | '_ / _` |    
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::            (v1.0.0.RC4)

2014-03-28 14:41:01.216  INFO 2852 --- [           main] c.PiranhaStorageServiceClientApplication : Starting PiranhaStorageServiceClientApplication on USDSFOSFC1NBOPY with PID 2852 (C:aworkspacesandboxs3-poc-clientargetclasses started by 310152252)
2014-03-28 14:41:01.220 DEBUG 2852 --- [           main] o.s.boot.SpringApplication               : Loading source class com.phi.piranha.client.config.PiranhaStorageServiceClientApplication
2014-03-28 14:41:01.270  INFO 2852 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6f434304: startup date [Fri Mar 28 14:41:01 PDT 2014]; root of context hierarchy
2014-03-28 14:41:01.273 DEBUG 2852 --- [           main] ationConfigEmbeddedWebApplicationContext : Bean factory for org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6f434304: org.springframework.beans.factory.support.DefaultListableBeanFactory@62b08658: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,piranhaStorageServiceClientApplication]; root of factory hierarchy
2014-03-28 14:41:01.897  INFO 2852 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'multipartResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=piranhaStorageServiceClientApplication; factoryMethodName=multipartResolver; initMethodName=null; destroyMethodName=(inferred); defined in class com.phi.piranha.client.config.PiranhaStorageServiceClientApplication] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration; factoryMethodName=multipartResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/MultipartAutoConfiguration.class]]
2014-03-28 14:41:02.188 DEBUG 2852 --- [           main] ationConfigEmbeddedWebApplicationContext : Using MessageSource [org.springframework.context.support.ResourceBundleMessageSource: basenames=[messages]]
2014-03-28 14:41:02.189 DEBUG 2852 --- [           main] ationConfigEmbeddedWebApplicationContext : Using ApplicationEventMulticaster [org.springframework.context.event.SimpleApplicationEventMulticaster@58a1c2bf]
2014-03-28 14:41:02.495 DEBUG 2852 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Code archive: C:Users310152252.m2
epositoryorgspringframeworkootspring-boot1.0.0.RC4spring-boot-1.0.0.RC4.jar
2014-03-28 14:41:02.495 DEBUG 2852 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Code archive: C:Users310152252.m2
epositoryorgspringframeworkootspring-boot1.0.0.RC4spring-boot-1.0.0.RC4.jar
2014-03-28 14:41:02.496 DEBUG 2852 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Document root: C:aworkspacesandboxs3-poc-clientsrcmainwebapp
2014-03-28 14:41:02.546  INFO 2852 --- [           main] .t.TomcatEmbeddedServletContainerFactory : Server initialized with port: 9090
2014-03-28 14:41:02.884  INFO 2852 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2014-03-28 14:41:02.885  INFO 2852 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.52
2014-03-28 14:41:03.077  INFO 2852 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2014-03-28 14:41:03.077  INFO 2852 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1811 ms
2014-03-28 14:41:03.810  INFO 2852 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2014-03-28 14:41:03.813  INFO 2852 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2014-03-28 14:41:04.356  INFO 2852 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-03-28 14:41:04.483  INFO 2852 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-03-28 14:41:04.483  INFO 2852 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2014-03-28 14:41:04.744  INFO 2852 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2014-03-28 14:41:04.763 DEBUG 2852 --- [           main] ationConfigEmbeddedWebApplicationContext : Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@11a91abc]
2014-03-28 14:41:04.765 DEBUG 2852 --- [           main] utoConfigurationReportLoggingInitializer : 


=========================
AUTO-CONFIGURATION REPORT
=========================


Positive matches:
-----------------

   MessageSourceAutoConfiguration
      - @ConditionalOnMissingBean (types: org.springframework.context.MessageSource; SearchStrategy: all) found no beans (OnBeanCondition)

   PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer
      - @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) found no beans (OnBeanCondition)

   JmxAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.jmx.export.MBeanExporter (OnClassCondition)
      - SpEL expression on org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration: ${spring.jmx.enabled:true} (OnExpressionCondition)
      - @ConditionalOnMissingBean (types: org.springframework.jmx.export.MBeanExporter; SearchStrategy: all) found no beans (OnBeanCondition)

   DispatcherServletAutoConfiguration
      - found web application StandardServletEnvironment (OnWebApplicationCondition)
      - @ConditionalOnClass classes found: org.springframework.web.servlet.DispatcherServlet (OnClassCondition)

   DispatcherServletAutoConfiguration.DispatcherServletConfiguration
      - no DispatcherServlet found (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition)
      - @ConditionalOnClass classes found: javax.servlet.ServletRegistration (OnClassCondition)

   EmbeddedServletContainerAutoConfiguration
      - found web application StandardServletEnvironment (OnWebApplicationCondition)

   EmbeddedServletContainerAutoConfiguration.EmbeddedTomcat
      - @ConditionalOnClass classes found: javax.servlet.Servlet,org.apache.catalina.startup.Tomcat (OnClassCondition)
      - @ConditionalOnMissingBean (types: org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; SearchStrategy: current) found no beans (OnBeanCondition)

   HttpMessageConvertersAutoConfiguration
      - @ConditionalOnClass classes found: org.springframework.http.converter.HttpMessageConverter (OnClassCondition)

   HttpMessageConvertersAutoConfiguration#messageConverters
      - @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.web.HttpMessageConverters; SearchStrategy: all) found no beans (OnBeanCondition)

   HttpMessageConvert

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I figured out that there is an issue with the MultipartAutoConfiguration within spring boot. I disabled it and added @Bean in the web config and it worked. Based on the exception I saw that the Jackson Mapper was trying to resolve the multipart content instead of the multipart resolver itself.

Here is the snippet.

@EnableAutoConfiguration(exclude={MultipartAutoConfiguration.class}

Add the following in your webconfig class

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
    logger.info("Loading the multipart resolver");
    CommonsMultipartResolver multipartResolver 
            = new CommonsMultipartResolver();
    return multipartResolver;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...