Spring Upload Mvc File Path to Db Store in Folder

File Uploading is a very common task in any web application. We take before seen how to upload files in Servlet and Struts2 File Uploading. Today we will acquire nigh Leap File upload, specifically Leap MVC File Upload for single and multiple files.

Spring MVC File Upload

Spring MVC framework provides support for uploading files by integrating Apache Commons FileUpload API. The process to upload files is very piece of cake and requires unproblematic configurations. Nosotros will create a unproblematic Spring MVC projection in STS that will await similar below image.

Spring File Uplaod Example Project, MultipartFile, MultipartResolver

Most of the part is the boiler-plate code generated past STS tool, we will focus on the changes that are required to utilize Spring file upload integration.

Maven Dependencies for Apache Commons FileUpload

First of all, nosotros need to add Apache Commons FileUpload dependencies in our pom.xml file, and so that required jar files are part of the spider web application. Beneath is the dependency snippet from my pom.xml file.

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

Spring File Upload Form Views

We will create two JSP pages to permit unmarried and multiple file uploads in leap web application.

upload.jsp view code:

                      <%@ taglib uri="https://coffee.sun.com/jsp/jstl/core" prefix="c" %> <%@ page session="fake" %> <html> <head> <championship>Upload File Request Folio</title> </head> <body> 	<course method="Mail" action="uploadFile" enctype="multipart/grade-information"> 		File to upload: <input type="file" name="file"><br />  		Proper name: <input blazon="text" name="name"><br /> <br />  		<input type="submit" value="Upload"> Press hither to upload the file! 	</form>	 </body> </html>                  

uploadMultiple.jsp view code:

                      <%@ taglib uri="https://java.sunday.com/jsp/jstl/cadre" prefix="c" %> <%@ page session="false" %> <html> <head> <title>Upload Multiple File Request Page</title> </head> <body> 	<grade method="POST" activeness="uploadMultipleFile" enctype="multipart/form-data"> 		File1 to upload: <input type="file" name="file"><br />  		Name1: <input type="text" name="proper noun"><br /> <br />  		File2 to upload: <input blazon="file" proper noun="file"><br />  		Name2: <input type="text" proper name="proper name"><br /> <br /> 		<input type="submit" value="Upload"> Press here to upload the file! 	</form> </trunk> </html>                  

Notice that these files are simple HTML files, I am not using any JSP or Spring tags to avoid complexity. The important point to note is that form enctype should be multipart/form-information, so that Leap web application knows that the request contains file data that needs to be processed.

Also notation that for multiple files, the class field "file" and "name" are the same in the input fields, so that the information volition be sent in the class of an array. We volition have the input array and parse the file information and store it in the given file proper noun.

Leap MVC Multipart Configuration

To utilize Apache Commons FileUpload for handling multipart requests, all nosotros demand to practice is configure multipartResolver bean with course as org.springframework.web.multipart.commons.CommonsMultipartResolver.

Our terminal Spring configuration file looks like below.

servlet-context.xml code:

                      <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="https://www.springframework.org/schema/mvc" 	xmlns:xsi="https://www.w3.org/2001/XMLSchema-example" 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://world wide web.springframework.org/schema/mvc/spring-mvc.xsd 		https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd 		https://world wide web.springframework.org/schema/context https://world wide web.springframework.org/schema/context/spring-context.xsd">  	<!-- DispatcherServlet Context: defines this servlet'southward request-processing  		infrastructure -->  	<!-- Enables the Spring MVC @Controller programming model --> 	<annotation-driven />  	<!-- Handles HTTP Become requests for /resource/** by efficiently serving  		up static resource in the ${webappRoot}/resources directory --> 	<resource mapping="/**" location="/" />  	<!-- Resolves views selected for rendering past @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:belongings proper noun="suffix" value=".jsp" /> 	</beans:bean>  	<beans:edible bean id="multipartResolver" 		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  		 <!-- setting maximum upload size --> 		<beans:property name="maxUploadSize" value="100000" />  	</beans:bean>  	<context:component-scan base-package="com.journaldev.spring.controller" />  </beans:beans>                  

Detect that I am setting maximum upload size limit by providing the maxUploadSize property value for multipartResolver edible bean. If you lot will wait into the source code of DispatcherServlet class, you lot will encounter that a MultipartResolver variable with proper name multipartResolver is divers and initialized in below method.

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

With this configuration, whatsoever request with enctype equally multipart/form-data will exist handled by multipartResolver before passing on to the Controller form.

Spring File Upload Controller Grade

Controller course lawmaking is very simple, we need to define handler methods for the uploadFile and uploadMultipleFile URIs.

FileUploadController.java code:

                      packet com.journaldev.spring.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.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.demark.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile;  /**  * Handles requests for the application file upload requests  */ @Controller public form FileUploadController {  	private static final Logger logger = LoggerFactory 			.getLogger(FileUploadController.grade);  	/** 	 * Upload single file using Leap Controller 	 */ 	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) 	public @ResponseBody 	Cord uploadFileHandler(@RequestParam("name") String proper noun, 			@RequestParam("file") MultipartFile file) {  		if (!file.isEmpty()) { 			attempt { 				byte[] bytes = file.getBytes();  				// Creating the directory to store file 				String rootPath = System.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 + proper noun); 				BufferedOutputStream stream = new BufferedOutputStream( 						new FileOutputStream(serverFile)); 				stream.write(bytes); 				stream.close();  				logger.info("Server File Location=" 						+ serverFile.getAbsolutePath());  				return "You successfully uploaded file=" + proper name; 			} catch (Exception e) { 				return "Y'all failed to upload " + name + " => " + e.getMessage(); 			} 		} else { 			render "Yous failed to upload " + name 					+ " considering the file was empty."; 		} 	}  	/** 	 * Upload multiple file using Jump Controller 	 */ 	@RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST) 	public @ResponseBody 	String uploadMultipleFileHandler(@RequestParam("proper noun") String[] names, 			@RequestParam("file") MultipartFile[] files) {  		if (files.length != names.length) 			render "Mandatory information missing";  		String bulletin = ""; 		for (int i = 0; i < files.length; i++) { 			MultipartFile file = files[i]; 			Cord proper noun = names[i]; 			try { 				byte[] bytes = file.getBytes();  				// Creating the directory to store file 				String 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());  				message = message + "You successfully uploaded file=" + name 						+ "<br />"; 			} catch (Exception e) { 				return "You failed to upload " + name + " => " + eastward.getMessage(); 			} 		} 		return message; 	} }                  

Notice the utilize of Bound annotations that make our life easier and code looks more than 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.

At present export the application every bit War file and deploy it into Tomcat servlet container.

When nosotros run our application, below images shows u.s.a. the request and responses.

Leap 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

Y'all can cheque the server logs to know the location where the files have been stored.

Download the projection from the above link and play around with it to learn more.

goodefelsou00.blogspot.com

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

0 Response to "Spring Upload Mvc File Path to Db Store in Folder"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel