Spring Mvc Uploaded File Is Null but Seeing Other Form Data

File Uploading is a very common task in whatever spider web application. We have earlier seen how to upload files in Servlet and Struts2 File Uploading. Today we will learn about Spring File upload, specifically Spring MVC File Upload for single and multiple files.

Leap MVC File Upload

Spring MVC framework provides back up for uploading files by integrating Apache Commons FileUpload API. The process to upload files is very easy and requires simple configurations. We volition create a simple Spring MVC project in STS that will wait like below epitome.

Spring File Uplaod Example Project, MultipartFile, MultipartResolver

About of the part is the banality-plate code generated by STS tool, nosotros will focus on the changes that are required to use Spring file upload integration.

Maven Dependencies for Apache Eatables FileUpload

Offset of all, we need to add Apache Commons FileUpload dependencies in our pom.xml file, so that required jar files are part of the web awarding. Below is the dependency snippet from my pom.xml file.

                      <!-- Apache Eatables FileUpload -->  <dependency> 	<groupId>commons-fileupload</groupId> 	<artifactId>commons-fileupload</artifactId> 	<version>1.3.1</version> </dependency>  <!-- Apache Commons IO -->  <dependency> 	<groupId>eatables-io</groupId> 	<artifactId>commons-io</artifactId> 	<version>2.4</version> </dependency>                  

Spring File Upload Form Views

We volition create two JSP pages to permit single and multiple file uploads in spring web application.

upload.jsp view lawmaking:

                      <%@ taglib uri="https://java.sun.com/jsp/jstl/cadre" prefix="c" %> <%@ page session="false" %> <html> <head> <championship>Upload File Request Page</title> </head> <body> 	<form method="Mail service" activeness="uploadFile" enctype="multipart/form-information"> 		File to upload: <input type="file" name="file"><br />  		Proper noun: <input type="text" proper name="proper noun"><br /> <br />  		<input type="submit" value="Upload"> Press hither to upload the file! 	</form>	 </trunk> </html>                  

uploadMultiple.jsp view code:

                      <%@ taglib uri="https://coffee.sun.com/jsp/jstl/core" prefix="c" %> <%@ folio session="false" %> <html> <head> <title>Upload Multiple File Request Page</title> </head> <body> 	<class method="POST" action="uploadMultipleFile" enctype="multipart/class-data"> 		File1 to upload: <input type="file" name="file"><br />  		Name1: <input type="text" name="name"><br /> <br />  		File2 to upload: <input type="file" name="file"><br />  		Name2: <input type="text" proper name="proper name"><br /> <br /> 		<input type="submit" value="Upload"> Printing here to upload the file! 	</form> </body> </html>                  

Observe that these files are simple HTML files, I am not using any JSP or Spring tags to avoid complication. The of import point to note is that form enctype should exist multipart/grade-information, and then that Spring web application knows that the asking contains file data that needs to be processed.

Also annotation that for multiple files, the grade field "file" and "name" are the same in the input fields, so that the information will exist sent in the class of an array. Nosotros will have the input array and parse the file data and store information technology in the given file name.

Spring MVC Multipart Configuration

To utilize Apache Commons FileUpload for handling multipart requests, all we demand to practice is configure multipartResolver edible bean with form every bit org.springframework.spider web.multipart.commons.CommonsMultipartResolver.

Our terminal Spring configuration file looks like beneath.

servlet-context.xml lawmaking:

                      <?xml version="1.0" encoding="UTF-viii"?> <beans:beans xmlns="https://world wide web.springframework.org/schema/mvc" 	xmlns:xsi="https://www.w3.org/2001/XMLSchema-case" xmlns:beans="https://www.springframework.org/schema/beans" 	xmlns:context="https://www.springframework.org/schema/context" 	xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd 		https://www.springframework.org/schema/beans https://world wide web.springframework.org/schema/beans/spring-beans.xsd 		https://www.springframework.org/schema/context https://world wide web.springframework.org/schema/context/spring-context.xsd">  	<!-- DispatcherServlet Context: defines this servlet's request-processing  		infrastructure -->  	<!-- Enables the Spring MVC @Controller programming model --> 	<notation-driven />  	<!-- Handles HTTP GET requests for /resources/** by efficiently serving  		up static resources in the ${webappRoot}/resources directory --> 	<resources mapping="/**" location="/" />  	<!-- Resolves views selected for rendering by @Controllers to .jsp resources  		in the /Web-INF/views directory --> 	<beans:bean 		class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 		<beans:property name="prefix" value="/WEB-INF/views/" /> 		<beans:property name="suffix" value=".jsp" /> 	</beans:bean>  	<beans:bean id="multipartResolver" 		class="org.springframework.spider web.multipart.commons.CommonsMultipartResolver">  		 <!-- setting maximum upload size --> 		<beans:property name="maxUploadSize" value="100000" />  	</beans:bean>  	<context:component-scan base-parcel="com.journaldev.bound.controller" />  </beans:beans>                  

Find that I am setting maximum upload size limit by providing the maxUploadSize belongings value for multipartResolver bean. If you volition look into the source code of DispatcherServlet class, you will run across that a MultipartResolver variable with name multipartResolver is divers and initialized in below method.

                      private void initMultipartResolver(ApplicationContext context)   {     try     {       this.multipartResolver = ((MultipartResolver)context.getBean("multipartResolver", MultipartResolver.form));       if (this.logger.isDebugEnabled()) {         this.logger.debug("Using MultipartResolver [" + this.multipartResolver + "]");       }     }     catch (NoSuchBeanDefinitionException ex)     {       this.multipartResolver = cipher;       if (this.logger.isDebugEnabled())         this.logger.debug("Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided");     }   }                  

With this configuration, whatever request with enctype as multipart/form-data will be handled past multipartResolver before passing on to the Controller form.

Spring File Upload Controller Grade

Controller class code is very uncomplicated, we demand to define handler methods for the uploadFile and uploadMultipleFile URIs.

FileUploadController.java code:

                      package com.journaldev.jump.controller;  import coffee.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream;  import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.spider web.demark.annotation.RequestMapping; import org.springframework.spider web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.spider web.multipart.MultipartFile;  /**  * Handles requests for the awarding file upload requests  */ @Controller public grade FileUploadController {  	private static final Logger logger = LoggerFactory 			.getLogger(FileUploadController.course);  	/** 	 * Upload single file using Spring Controller 	 */ 	@RequestMapping(value = "/uploadFile", method = RequestMethod.Mail) 	public @ResponseBody 	String uploadFileHandler(@RequestParam("proper name") Cord name, 			@RequestParam("file") MultipartFile file) {  		if (!file.isEmpty()) { 			try { 				byte[] bytes = file.getBytes();  				// Creating the directory to shop file 				Cord rootPath = Organisation.getProperty("catalina.home"); 				File dir = new File(rootPath + File.separator + "tmpFiles"); 				if (!dir.exists()) 					dir.mkdirs();  				// Create the file on server 				File serverFile = new File(dir.getAbsolutePath() 						+ File.separator + name); 				BufferedOutputStream stream = new BufferedOutputStream( 						new FileOutputStream(serverFile)); 				stream.write(bytes); 				stream.close();  				logger.info("Server File Location=" 						+ serverFile.getAbsolutePath());  				return "You successfully uploaded file=" + name; 			} catch (Exception e) { 				return "You failed to upload " + proper name + " => " + e.getMessage(); 			} 		} else { 			return "You failed to upload " + proper name 					+ " because the file was empty."; 		} 	}  	/** 	 * Upload multiple file using Spring Controller 	 */ 	@RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.Mail service) 	public @ResponseBody 	String uploadMultipleFileHandler(@RequestParam("name") String[] names, 			@RequestParam("file") MultipartFile[] files) {  		if (files.length != names.length) 			return "Mandatory information missing";  		String bulletin = ""; 		for (int i = 0; i < files.length; i++) { 			MultipartFile file = files[i]; 			Cord name = names[i]; 			effort { 				byte[] bytes = file.getBytes();  				// Creating the directory to store file 				Cord rootPath = System.getProperty("catalina.dwelling house"); 				File dir = new File(rootPath + File.separator + "tmpFiles"); 				if (!dir.exists()) 					dir.mkdirs();  				// Create the file on server 				File serverFile = new File(dir.getAbsolutePath() 						+ File.separator + proper name); 				BufferedOutputStream stream = new BufferedOutputStream( 						new FileOutputStream(serverFile)); 				stream.write(bytes); 				stream.close();  				logger.info("Server File Location=" 						+ serverFile.getAbsolutePath());  				message = message + "You successfully uploaded file=" + proper noun 						+ "<br />"; 			} catch (Exception eastward) { 				return "You failed to upload " + proper noun + " => " + e.getMessage(); 			} 		} 		return bulletin; 	} }                  

Notice the use of Spring annotations that make our life easier and code looks more readable.

uploadFileHandler method is used to handle single file upload scenario whereas uploadMultipleFileHandler method is used to handle multiple files upload scenario. Actually we could have a single method to handle both the scenarios.

Now export the awarding as WAR file and deploy information technology into Tomcat servlet container.

When we run our application, beneath images shows us the request and responses.

Bound MVC File Upload Case

Spring MVC Single File Upload Form

Spring MVC Single File Upload Response

Spring MVC Multiple File Upload Example

Spring Multiple File Upload Response

You can bank check the server logs to know the location where the files have been stored.

Download the project from the higher up link and play around with information technology to acquire more.

childershillieve.blogspot.com

Source: https://www.journaldev.com/2573/spring-mvc-file-upload-example-single-multiple-files

0 Response to "Spring Mvc Uploaded File Is Null but Seeing Other Form Data"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel