Spring mvc multiple file upload with progress bar in ajax and jquery

This spring 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 post on spring MVC multiple file upload example which didn’t had progress bar feature, rather that displayed the uploaded image and data in new display page.

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

1. Client view for file upload and progress bar

Below given productForm.jsp is a JSP file in spring MVC project – but it contains only HTML code so you can easily place the same code if you want it that way.

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>
	var totalFileLength, totalUploaded, fileCount, filesUploaded;

	//To log everything on console
	function debug(s) {
		var debug = document.getElementById('debug');
		if (debug) {
			debug.innerHTML = debug.innerHTML + '<br/>' + s;

	//Will be called when upload is completed
	function onUploadComplete(e) {
		totalUploaded += document.getElementById('files').files[filesUploaded].size;
		debug('complete ' + filesUploaded + " of " + fileCount);
		debug('totalUploaded: ' + totalUploaded);
		if (filesUploaded < fileCount) {
		} else {
			var bar = document.getElementById('bar');
			bar.style.width = '100%';
			bar.innerHTML = '100% complete';
			alert('Finished uploading file(s)');

	//Will be called when user select the files in file control
	function onFileSelect(e) {
		var files = e.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(), ')');
			debug('add ' + file.size);
			totalFileLength += file.size;
		document.getElementById('selectedFiles').innerHTML = output.join('');
		debug('totalFileLength:' + totalFileLength);

	//This will continueously update the progress bar
	function onUploadProgress(e) {
		if (e.lengthComputable) {
			var percentComplete = parseInt((e.loaded + totalUploaded) * 100	/ totalFileLength);
			var bar = document.getElementById('bar');
			bar.style.width = percentComplete + '%';
			bar.innerHTML = percentComplete + ' % complete';
		} else {
			debug('unable to compute');

	//the Ouchhh !! moments will be captured here
	function onUploadFailed(e) {
		alert("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, false);
		xhr.addEventListener("load", onUploadComplete, false);
		xhr.addEventListener("error", onUploadFailed, false);
		xhr.open("POST", "save-product");
		debug('uploading ' + file.name);

	//Let's begin the upload process
	function startUpload() {
		totalUploaded = filesUploaded = 0;

	//Event listeners for button clicks
	window.onload = function() {
		document.getElementById('files').addEventListener('change', onFileSelect, false);
		document.getElementById('uploadButton').addEventListener('click', startUpload, false);
	<div style="width:55%">  
		<h1>HTML5 Ajax Multi-file Upload With Progress Bar</h1>
		<div id='progressBar' style='height: 20px; border: 2px solid green; margin-bottom: 20px'>
			<div id='bar' style='height: 100%; background: #33dd33; width: 0%'>
		<form style="margin-bottom: 20px">
			<input type="file" id="files" multiple style="margin-bottom: 20px"/><br/>
			<output id="selectedFiles"></output>
			<input id="uploadButton" type="button" value="Upload" style="margin-top: 20px"/>
		<div id='debug' style='height: 100px; border: 2px solid #ccc; overflow: auto'></div>

2. Discussion on upload progress feature

Above code is enough self explanatory and you should not face any problem in understanding. But let’s summarize the points :

  1. The “Upload” 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 be uploaded, and filesUploaded indicates the number of files that have been uploaded.
  3. window.onload() maps the files input element’s change event with the onFileSelect function and the button’s click event with startUpload.
  4. When the user clicks the Upload button, the startUpload function is called and it in turns calls the uploadNext function. uploadNext uploads the next file in the selected file collection. 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 event 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 called repeatedly, giving it the opportunity to update the progress bar.
  7. At the completion of an upload, the onUploadComplete function is invoked.

3. Multiple File Upload Controller and Model Class

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

3.1. 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.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.howtodoinjava.demo.model.UploadedFile;

public class DemoProductController 
    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);
        } catch (IOException e) {
	@RequestMapping(value = "/product-input-form")
    public String inputProduct(Model model) {
        return "productForm";

3.2. Spring MVC multiple file model class

package com.howtodoinjava.demo.model;

import org.springframework.web.multipart.MultipartFile;

public class UploadedFile {
	private static final 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

4.1. web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 

	<display-name>Spring Web MVC Hello World Application</display-name>



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"

	<context:component-scan base-package="com.howtodoinjava.demo" />
	<mvc:resources mapping="/image/**" location="/image/" />

	<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 name="suffix" value=".jsp" />
	<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
	    <property name="basename" value="messages" />
	<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"></bean>

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 Button
  • If everything goes right, then you will get upload progress bar and uploaded file information as 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 Spring mvc multiple file upload with progress bar example.

Happy Learning !!


Notify of
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.