Spring Mvc Supports Only Commonsmultipartresolver for Uploading File
In thisLeap MVC Multiple File Upload Example, nosotros will learn how to upload multiple files in Spring MVC usingCommonsMultipartResolver. We must add the Apache Commons File Upload dependency (commons-fileupload.jar) in lodge to useCommonsMultipartResolver.
Spring by default will not handle multipart file uploads, still it provides the support to multipart using the pluggable multipart object called"MultipartResolver". We will have to be enabling the MultipartResolver in the context, in our case it isCommonsMultipartResolver.
Once we have enabled the MultipartResolver in the context each asking volition be checked whether it has a multipart in it, if present then the configuredCommonsMultipartResolver volition be used.
Folder Construction:
- Create a uncomplicatedMaven webapp Projection"SpringMVCFileUpload" and create a bundle for our source files "com.javainterviewpoint" under src/master/java
- Now add together the following dependency in the POM.xml
<projection xmlns="http://maven.apache.org/POM/four.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-case" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javainterviewpoint</groupId> <artifactId>SpringMVCFileUpload</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>Spring MVC Multiple File Upload Example</proper name> <url>http://maven.apache.org</url> <properties> <jdk.version>1.8</jdk.version> <leap.version>4.3.7.RELEASE</spring.version> <jstl.version>1.2</jstl.version> <servlet.version>3.1.0</servlet.version> <commons.fileupload.version>1.3.2</commons.fileupload.version> </backdrop> <dependencies> <!-- Spring MVC Dependency --> <dependency> <groupId>org.springframework</groupId> <artifactId>jump-webmvc</artifactId> <version>${jump.version}</version> </dependency> <!-- Apache Commons file upload Dependency--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${eatables.fileupload.version}</version> </dependency> <!-- JSTL Dependency --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <!-- Servlet Dependency --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>SpringMVCFileUpload</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> </configuration> </plugin> </plugins> </build> </project> - Create the Java grade UploadController.java,WebApplicationInitializer.java and SpringWebMvcConfig.java under com.javainterviewpointfolder.
- Identify the uploadForm.jsp under the sub directory under Spider web-INF/Jsp
Spring MVC Multiple File Upload Example
Dependency Tree
[INFO] ------------------------------------------------------------------------ [INFO] Edifice Spring MVC Multiple File Upload Example 0.0.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- maven-dependency-plugin:two.8:tree (default-cli) @ SpringMVCFileUpload --- [INFO] com.javainterviewpoint:SpringMVCFileUpload:war:0.0.1-SNAPSHOT [INFO] +- org.springframework:spring-webmvc:jar:4.iii.7.RELEASE:compile [INFO] | +- org.springframework:spring-aop:jar:4.3.7.RELEASE:compile [INFO] | +- org.springframework:spring-beans:jar:4.iii.seven.RELEASE:compile [INFO] | +- org.springframework:spring-context:jar:4.3.vii.RELEASE:compile [INFO] | +- org.springframework:spring-core:jar:iv.3.vii.RELEASE:compile [INFO] | | \- commons-logging:commons-logging:jar:ane.2:compile [INFO] | +- org.springframework:spring-expression:jar:4.iii.7.RELEASE:compile [INFO] | \- org.springframework:jump-spider web:jar:4.iii.7.RELEASE:compile [INFO] +- eatables-fileupload:commons-fileupload:jar:one.3.2:compile [INFO] | \- commons-io:eatables-io:jar:two.2:compile [INFO] +- jstl:jstl:jar:1.ii:compile [INFO] \- javax.servlet:javax.servlet-api:jar:3.1.0:provided [INFO] ------------------------------------------------------------------------
WebMvcConfiguration.coffee
Create our SpringWebMvcConfig .java nether the com.javainterviewpoint packet.
package com.javainterviewpoint; import org.springframework.context.notation.Edible bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.multipart.eatables.CommonsMultipartResolver; import org.springframework.spider web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @Configuration @ComponentScan({"com.javainterviewpoint"}) public grade SpringWebMvcConfig extends WebMvcConfigurerAdapter { @Edible bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.grade); viewResolver.setPrefix("/Web-INF/Jsp"); viewResolver.setSuffix(".jsp"); return viewResolver; } @Bean public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver resolver= new CommonsMultipartResolver(); resolver.setMaxUploadSize(1048576); //1MB render cmr; } } - We take created the new instance for the CommonsMultipartResolver and have gear up the setMaxUploadSize to permit just 1 MB.
- Whenever the DispatcherServlet detects a multipart asking, it activates the CommonsMultipartResolver which is declared in the Spring Context.
- The MultipartResolver then wraps the plainHttpServletRequest into a MultipartHttpServletRequest which has back up for multipart file uploads.
We have annotated ourWebMvcConfiguration form with the beneath annotation
- @Configuration indicates that our SpringWebMvcConfig form can exist used by the Spring IoC container as a source of bean definitions.
- @EnableWebMvc is equivalent to <mvc:annotation-driven /> in XML. It enables back up for @Controller annotated classes. This annotation imports configuration from WebMvcConfigurationSupport
- @ComponentScan scans the stereotype annotations specified in @Controller, @Service etc.. annotated classes.
Equivalent XML configuration – SpringConfig-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://world wide web.springframework.org/schema/p" xmlns:context="http://world wide web.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://world wide web.springframework.org/schema/beans http://www.springframework.org/schema/beans/jump-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/leap-mvc.xsd"> <context:component-scan base of operations-package="com.javainterviewpoint"> </context:component-scan> <mvc:annotation-driven> </mvc:annotation-driven> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <holding name="prefix" value="/Spider web-INF/Jsp/"></holding> <property proper noun="suffix" value=".jsp"></property> </edible bean> <bean id="multipartResolver" class="org.springframework.spider web.multipart.commons.CommonsMultipartResolver"> <!-- Setting the Maximum upload size to 1MB --> <holding name="maxUploadSize" value="1048576" /> </bean> </beans>
WebApplicationInitializer.coffee
We can use AbstractAnnotationConfigDispatcherServletInitializer class to register and initialize the DispatcherServletwhen the Servlet used in greater than 3.0 (No need for spider web.xml)
package com.javainterviewpoint; import org.springframework.spider web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public form WebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getServletConfigClasses() { return new Form[]{SpringWebMvcConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } @Override protected Course<?>[] getRootConfigClasses() { return aught; } } Equivalent XML configuration – web.xml
<spider web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>SpringConfig</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-course> <init-param> <param-name>contextConfigLocation</param-name> <param-value></param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-proper noun>SpringConfig</servlet-proper name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/SpringConfig-servlet.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-grade> </listener> </web-app>
UploadController.java
package com.javainterviewpoint; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import coffee.io.IOException; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.multipart.MultipartFile; @Controller public grade UploadController { @GetMapping("/") public String showUploadForm(Model model) { return "uploadForm"; } @PostMapping("/salve") public String saveFiles(@ModelAttribute("uploadFiles") FileData fileData, Model model) throws IOException { //Get the listing of files List files = fileData.getFiles(); //Check whether the list is not null or empty if (files != null && !files.get(0).getOriginalFilename().isEmpty()) { //Get the private MultipartFile for (MultipartFile multipartFile : files) { //Write each MultipartFile in the directory specified if (!multipartFile.getOriginalFilename().isEmpty()) { BufferedOutputStream outputStream = new BufferedOutputStream( new FileOutputStream(new File("E:\\JIP\\", multipartFile.getOriginalFilename()))); outputStream.write(multipartFile.getBytes()); outputStream.flush(); outputStream.close(); } } model.addAttribute("message", "All Files are uploaded successfully!!"); } else { model.addAttribute("message", "Please select atleast one file!!"); } return "uploadForm"; } } - We take annotated our "UploadController" class with @Controller note which tells Spring Container to treat this class every bit a Controller.
- @GetMapping annotation on top of showUploadForm()redirects the request to this method, when the request given is "/"and information technology tin can have only GET asking and redirects the user to the uploadForm.jsp
- In one case the user submits the form, the saveFiles() method will be called, it gets the form data using @ModelAttribute and in-turn iterates each MultipartFile and writes to the new directory.
uploadForm.jsp
The uploadForm.jsp should be created under /Spider web-INF/Jsp binder.
<%@ taglib uri="http://world wide web.springframework.org/tags/form" prefix="form"%> <html> <body> <h1>Jump MVC Multiple File Upload Instance</h1> <form:grade method="Mail" action="save" modelAttribute="uploadFiles" enctype="multipart/class-information"> <input type="file" proper noun="files" /> <br><br> <input blazon="file" name="files" /> <br><br> <input blazon="submit" value="Submit" /> </form:form> <br> <60 minutes /> <h3 style="colour: ruby;">${message}</h3> </torso> </html> In form, the modelAttribute holds the form data using FileData bean and we have also nosotros have added the encoding aspect (enctype="multipart/course-data") which is necessary to let the browser know how to encode the multipart fields
Output
One time the server is started, hit on the url : http://localhost:8080/SpringMVCFileUpload/
When the user hits on submit button without selecting a single file, the beneath error message will exist thrown
On successful upload
Download Source Code
Source: https://www.javainterviewpoint.com/spring-mvc-multiple-file-upload/
0 Response to "Spring Mvc Supports Only Commonsmultipartresolver for Uploading File"
Enregistrer un commentaire