Spring Mvc Multiple File Upload With Progress

This bound mvc example demonstrate the use of multiple file upload functionality with progress bar while the server side code is written in spring MVC. I have modified the code written for previous mail on spring MVC multiple file upload instance which didn't had progress bar feature, rather that displayed the uploaded prototype and information in new display page.

This example uses pure javascript lawmaking and HTML5 controls to build client side code. If you want to employ any javascript library e.g. jQuery then please modify the code accordingly.

1. Client view for file upload and progress bar

Beneath given productForm.jsp is a JSP file in spring MVC project – but information technology contains only HTML lawmaking so you tin easily place the same code if you want it that fashion.

This file has onUploadProgress() function which displays the progress of uploaded files. There are other functions to display completion of upload process and supporting activities.

<!DOCTYPE html> <html> <caput> <script> 	var totalFileLength, totalUploaded, fileCount, filesUploaded;  	//To log everything on console 	role debug(southward) { 		var debug = certificate.getElementById('debug'); 		if (debug) { 			debug.innerHTML = debug.innerHTML + '<br/>' + s; 		} 	}  	//Volition be chosen when upload is completed 	function onUploadComplete(e) { 		totalUploaded += document.getElementById('files').files[filesUploaded].size; 		filesUploaded++; 		debug('complete ' + filesUploaded + " of " + fileCount); 		debug('totalUploaded: ' + totalUploaded); 		if (filesUploaded < fileCount) { 			uploadNext(); 		} else { 			var bar = document.getElementById('bar'); 			bar.style.width = '100%'; 			bar.innerHTML = '100% complete'; 			alert('Finished uploading file(due south)'); 		} 	}  	//Volition be called when user select the files in file control 	part onFileSelect(e) { 		var files = due east.target.files; // FileList object 		var output = []; 		fileCount = files.length; 		totalFileLength = 0; 		for (var i = 0; i < fileCount; i++) { 			var file = files[i]; 			output.push(file.name, ' (', file.size, ' bytes, ', file.lastModifiedDate.toLocaleDateString(), ')'); 			output.push button('<br/>'); 			debug('add together ' + file.size); 			totalFileLength += file.size; 		} 		certificate.getElementById('selectedFiles').innerHTML = output.join(''); 		debug('totalFileLength:' + totalFileLength); 	}  	//This volition continueously update the progress bar 	function onUploadProgress(e) { 		if (due east.lengthComputable) { 			var percentComplete = parseInt((e.loaded + totalUploaded) * 100	/ totalFileLength); 			var bar = document.getElementById('bar'); 			bar.fashion.width = percentComplete + '%'; 			bar.innerHTML = percentComplete + ' % complete'; 		} else { 			debug('unable to compute'); 		} 	}  	//the Ouchhh !! moments will be captured here 	part onUploadFailed(east) { 		alarm("Error uploading file"); 	}  	//Pick the next file in queue and upload it to remote server 	function uploadNext() { 		var xhr = new XMLHttpRequest(); 		var fd = new FormData(); 		var file = document.getElementById('files').files[filesUploaded]; 		fd.append("multipartFile", file); 		xhr.upload.addEventListener("progress", onUploadProgress, faux); 		xhr.addEventListener("load", onUploadComplete, false); 		xhr.addEventListener("error", onUploadFailed, faux); 		xhr.open("POST", "save-product"); 		debug('uploading ' + file.proper noun); 		xhr.transport(fd); 	}  	//Let'due south begin the upload process 	function startUpload() { 		totalUploaded = filesUploaded = 0; 		uploadNext(); 	}  	//Outcome listeners for button clicks 	window.onload = function() { 		certificate.getElementById('files').addEventListener('change', onFileSelect, faux); 		document.getElementById('uploadButton').addEventListener('click', startUpload, false); 	} </script> </head> <body> 	<div style="width:55%">   		<h1>HTML5 Ajax Multi-file Upload With Progress Bar</h1> 		<div id='progressBar' mode='summit: 20px; border: 2px solid green; margin-bottom: 20px'> 			<div id='bar' style='height: 100%; background: #33dd33; width: 0%'> 			</div> 		</div> 		<form style="margin-bottom: 20px"> 			<input blazon="file" id="files" multiple style="margin-bottom: 20px"/><br/> 			<output id="selectedFiles"></output> 			<input id="uploadButton" type="button" value="Upload" style="margin-top: 20px"/> 		</form> 		<div id='debug' fashion='height: 100px; border: 2px solid #ccc; overflow: auto'></div> 	</div> </torso> </html>        

two. Discussion on upload progress feature

To a higher place code is enough self explanatory and y'all should non confront any problem in understanding. But let's summarize the points :

  1. The "Upload" push button is not a submit button. So, clicking it will not submit the containing form. In fact, the script uses the XMLHttpRequest object to do the upload.
  2. The totalFileLength variable holds the total length of the files to be uploaded. totalUploaded is the number of bytes uploaded so far. fileCount contains the number of files to exist uploaded, and filesUploaded indicates the number of files that have been uploaded.
  3. window.onload() maps the files input chemical element's modify event with the onFileSelect function and the button's click event with startUpload.
  4. When the user clicks the Upload button, the startUpload part is called and it in turns calls the uploadNext function. uploadNext uploads the next file in the selected file drove. It starts by creating an XMLHttpRequest object and a FormData object to which the file to be uploaded next is appended to.
  5. The uploadNext function then attaches the progress outcome of the XMLHttpRequest object to the onUploadProgress and the load event and the error event to onUploadComplete and onUploadFailed, respectively.
  6. During the upload progress, the onUploadProgress function is chosen repeatedly, giving it the opportunity to update the progress bar.
  7. At the completion of an upload, the onUploadComplete office is invoked.

three. Multiple File Upload Controller and Model Form

The Jump MVC file upload controller and model classes are given below:

3.one. Spring MVC multiple file upload controller

package com.howtodoinjava.demo.controller;  import java.io.File; import java.io.IOException;  import javax.servlet.http.HttpServletRequest;  import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.spider web.bind.notation.RequestMapping; import org.springframework.web.multipart.MultipartFile;  import com.howtodoinjava.demo.model.UploadedFile;  @Controller public class DemoProductController  { 	@RequestMapping("/salvage-product")     public void saveFile(HttpServletRequest servletRequest,             @ModelAttribute UploadedFile uploadedFile,             BindingResult bindingResult, Model model) {          MultipartFile multipartFile = uploadedFile.getMultipartFile();         String fileName = multipartFile.getOriginalFilename();         try {             File file = new File(servletRequest.getServletContext().getRealPath("/image"), fileName);             multipartFile.transferTo(file);         } catch (IOException e) {             eastward.printStackTrace();         }     } 	 	@RequestMapping(value = "/production-input-form")     public String inputProduct(Model model) {         return "productForm";     } }        

three.two. Spring MVC multiple file model course

package com.howtodoinjava.demo.model;  import org.springframework.web.multipart.MultipartFile;  public grade UploadedFile { 	individual static concluding long serialVersionUID = 1L;     private MultipartFile multipartFile;     public MultipartFile getMultipartFile() {         return multipartFile;     }     public void setMultipartFile(MultipartFile multipartFile) {         this.multipartFile = multipartFile;     } }        

4. Other files used to build example

four.i. web.xml

<?xml version="i.0" encoding="UTF-8"?> <web-app version="three.ane"      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">  	 	<display-proper name>Leap Spider web MVC Hullo Earth Awarding</display-proper noun> 	 	<servlet> 		<servlet-name>spring</servlet-name> 		<servlet-class> 			org.springframework.web.servlet.DispatcherServlet 		</servlet-class> 		<multipart-config> 	        <max-file-size>20848820</max-file-size> 	        <max-request-size>418018841</max-request-size> 	        <file-size-threshold>1048576</file-size-threshold> 	    </multipart-config>     	</servlet>  	<servlet-mapping> 		<servlet-proper name>spring</servlet-name> 		<url-design>/</url-pattern> 	</servlet-mapping>  </web-app>        

4.2. spring-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans" 	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 	xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/leap-beans-3.0.xsd         http://www.springframework.org/schema/context/         http://world wide web.springframework.org/schema/context/leap-context-3.0.xsd         http://www.springframework.org/schema/mvc/         http://world wide web.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  	<context:component-browse base of operations-bundle="com.howtodoinjava.demo" /> 	 	<mvc:resources mapping="/image/**" location="/paradigm/" />  	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> 	<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> 	 	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 		<property name="prefix" value="/Web-INF/views/" /> 		<property proper name="suffix" value=".jsp" /> 	</edible bean> 	 	<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 	    <property proper name="basename" value="messages" /> 	</bean> 	 	<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></bean> 	 </beans>        

5. Spring mvc multiple file upload with progress bar demo

  • Hit the URL: http://localhost:8080/springmvcexample/product-input-form

    Below screen will load on browser.

    Multi-file Upload With Progress Bar - Input Form
    Multi-file Upload With Progress Bar – Input Form
  • Select Files and Click Upload Push button
  • If everything goes correct, then you will go upload progress bar and uploaded file information every bit below.
    Multi-file Upload With Progress Bar - Upload Success
    Multi-file Upload With Progress Bar – Upload Success

Drop me your queries and questions related to Bound mvc multiple file upload with progress bar case.

Happy Learning !!

brownriggouggialk.blogspot.com

Source: https://howtodoinjava.com/spring-mvc/spring-mvc-multi-file-upload-with-progress-bar/

0 Response to "Spring Mvc Multiple File Upload With Progress"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel