This example shows how to use StandardServletMultipartResolver to upload a file. This resolver is based on the Servlet 3.0 javax.servlet.http.Part API.
Also check out this tutorial to understand how MultipartResolver works.
Other than registering StandardServletMultipartResolver as a bean, we also need to set a javax.servlet.MultipartConfigElement on the Servlet registration which does configuration equivalent to using javax.servlet.annotation.MultipartConfig annotation. Check out this related Servlet example.
Example
We are going to reuse our last example, we just need to modify our Java Config and WebApplicationInitializer implementation.
Java Config
@EnableWebMvc
@Configuration
@Import(MyViewConfig.class)
public class MyWebConfig {
@Bean
public MultipartResolver multipartResolver() {
StandardServletMultipartResolver resolver = new StandardServletMultipartResolver();
//resolver.setResolveLazily(true);
return resolver;
}
@Bean
public FileUploadController uploadController() {
return new FileUploadController();
}
}
public class MyWebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx =
new AnnotationConfigWebApplicationContext();
ctx.register(MyWebConfig.class);
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet =
servletContext.addServlet("springDispatcherServlet",
new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
//using MultipartConfigElement(location,maxFileSize,maxRequestSize,fileSizeThreshold)
MultipartConfigElement multipartConfig = new MultipartConfigElement(
"c:/temp", 50000000, 50000000, 0);
//new MultipartConfigElement("c:/temp") will create unlimited sizes and 0 threshold
servlet.setMultipartConfig(multipartConfig);
}
}
To try examples, run embedded tomcat (configured in pom.xml of example project below):
mvn tomcat7:run-war
Output
Output of this example is same as the last example.
Using javax.servlet.http.Part
When using StandardServletMultipartResolver , instead of MultipartFile/MultipartHttpServletRequest as the controller's handler method argument, we can alternatively use javax.servlet.http.Part . Complete example here
Example ProjectDependencies and Technologies Used: - spring-webmvc 4.2.4.RELEASE: Spring Web MVC.
- spring-test 4.2.4.RELEASE: Spring TestContext Framework.
- javax.servlet-api 3.0.1 Java Servlet API
- jstl 1.2 javax.servlet:jstl
- junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
- JDK 1.8
- Maven 3.3.9
|