Java file upload with progress bar Ajax [Step-by-step]

In this article, we will see how do you create a Java file upload with an advanced progress bar using Ajax. This article explained you to create a Maven application in Eclipse IDE step by step. Here we are going to use the below software dependencies to develop this application.

Software Dependency

Let’s start it now. Follow the below steps:

Step-1. Open Eclipse IDE

Once you open the eclipse, it will ask for the Workspace. As you can see in the below image we are taking F:\Websites\Javacodepoint\Projects as a Workspace.

Java file upload ajax - Select a workspace

Step-2. Create New Project

After opening eclipse IDE in the selected workspace click on File menu > New > Dynamic Web Project as below image:

Java file upload ajax - create new project

After clicking on “Dynamic Web Project”, It will ask you to type Project name. Type the Project name: AdvFileUploadJava and click on the Finish button as below image:

Java file upload ajax - Dynamic web project dialog

Now you can able to see the below eclipse project structure got created:

Java file upload ajax - eclipse project structure

Step-3. Convert Project to Maven Project

Now Just Right-click on “AdvFileUploadJava” Project > Configure > Convert to Maven Project as below image:

Java file upload ajax - Convert to maven project

Once you click on Convert to Maven Project, you will see the below image, Here type Group Id: com.javacodepoint and click on the Finish button.

Java file upload ajax - create new pom dialog

Now you can able to see the Project got successfully converted to Maven Project as below eclipse structure:

Java file upload ajax - eclipse maven project structure

Step-4. Add Maven Dependency

In pom.xml, you need to add below javax.servlet-api maven dependency or copy the entire below pom.xml content:



<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">

Step-5. Create New Java Package

Right-click on src > New > Package as below image:

Java file upload ajax - create new java package

Once you click on “Package”, It will ask you to type Package name. Here you can type Name: com.javacodepoint.fileupload and click on the Finish button as below image:

Java file upload ajax - new java package dialog

Step-6. Create Servlet Class

Right click on created Package(com.javacodepoint.fileupload) > New > Class as below image:

Java file upload ajax - create new java class

Once you click on “Class”, It will ask you to type Class name. Here you can type Name: FileUploadServlet and click on the Finish button.

Java file upload ajax - new java class dialog

Now copy the below file content and paste it in file:

package com.javacodepoint.fileupload;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
 * @author javacodepoint
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
        maxFileSize = 1024 * 1024 * 500, // 500MB
        maxRequestSize = 1024 * 1024 * 1024) // 1GB
public class FileUploadServlet extends HttpServlet {
     * Location to save uploaded files on server
    private static final String UPLOAD_PATH = "C:/uploads";
     * Method to get file name from HTTP header content-disposition
    private String getFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String s : items) {
            if (s.trim().startsWith("filename")) {
                return s.substring(s.indexOf("=") + 2, s.length() - 1);
        return null;
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            File uploadsPath = new File(UPLOAD_PATH);
            if (!uploadsPath.exists()) {
                //create upload folder if not exist.
            for (Part part : request.getParts()) {
                String fileName = getFileName(part);
                if(fileName!=null) {
                    part.write(UPLOAD_PATH + File.separator + fileName);
            System.out.println("File uploaded successfully!");
        } catch (Exception e) {
            System.err.println("Error while uploading files!");

Step-7. Create HTML file

This file contains the Html as well as Javascript Ajax code. To create it, Right-click on WebContent > New > HTML File as below image:

Java file upload ajax -create new html file
Java file upload ajax -new html file dialog

Now give the File name: filesupload.html and click on the Finish button as above image. After that copy the below file content into the filesupload.html file.


<!DOCTYPE PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<link rel="stylesheet"
<link rel="stylesheet"
<script src=""></script>
.table>tbody>tr>td{padding: 2px 6px;vertical-align: middle;border:none;}
#main-container{padding: 0px 20px 40px; width: 50%;margin:auto;}
#upload-header{height:35px;width:100%;background-color: #323254;color: #fff;padding: 8px;border-top-left-radius: 10px;border-top-right-radius: 10px;}
#progress-bar-container{padding:20px;max-height:260px;overflow-y:auto;border:1px solid #323254;}
::-webkit-scrollbar {background-color: #fff; width: 8px; height: 8px;}
::-webkit-scrollbar-thumb {background-color: #C0C0C0; border-radius: 10px;}
    <div id="main-container">
        <h3 class="text-info">Advance progress-bar file upload using Ajax</h3>
        <div style="margin-bottom: 20px">
            <input type="file" id="files" multiple style="margin-bottom: 20px" />
            <button class="btn btn-primary" type="button" onclick="startUploading()" ><i class="fa fa-upload"></i> Upload file</button>
        <div id="upload-status-container">
            <div id="upload-header">
                <span id="upload-header-text"></span>
                <i class="action-icon fa fa-window-minimize pull-right" onclick="showHide(this)" title="minimize"></i>
            <div id="progress-bar-container">
                <table class="table">
    /* Globle variables */
    var totalFileCount, fileUploadCount, fileSize;
    /* start uploading files */
    function startUploading() {
        var files = document.getElementById('files').files;
            alert("Please choose at least one file and try.");
        // upload through ajax call     
    /* This method will be called to prepare progress-bar UI */
    function prepareProgressBarUI(files){
        totalFileCount = files.length;
        var $tbody=$("#progress-bar-container").find("tbody");
        $("#upload-header-text").html("1 of "+totalFileCount+" file(s) is uploading");
        for(var i=0;i<totalFileCount;i++){
            var fsize=parseFileSize(files[i].size);
            var fname=files[i].name;
            var bar='<tr id="progress-bar-'+i+'"><td style="width:75%"><div class="filename">'+fname+'</div>'
            +'<div class="progress"><div class="progress-bar progress-bar-striped active" style="width:0%"></div></div></td>'
            +'<td  style="width:25%"><span class="size-loaded"></span> '+fsize+' <span class="percent-loaded"></span></td></tr>';
    /* parse the file size in kb/mb/gb */
    function parseFileSize(size){
        var precision=1;
        var factor = Math.pow(10, precision);
        size = Math.round(size / 1024); //size in KB
        if(size < 1000){
            return size+" KB";
            size = Number.parseFloat(size / 1024); //size in MB
            if(size < 1000){
                return (Math.round(size * factor) / factor) + " MB";
                size = Number.parseFloat(size / 1024); //size in GB
                return (Math.round(size * factor) / factor) + " GB";
        return 0;
    /* one by one file will be uploaded to the server by ajax call*/
    function uploadFile() {
        var file = document.getElementById('files').files[fileUploadCount];
        fileSize = file.size;
        var xhr = new XMLHttpRequest();
        var fd = new FormData();
        fd.append("multipartFile", file);
        xhr.upload.addEventListener("progress", onUploadProgress, false);
        xhr.addEventListener("load", onUploadComplete, false);
        xhr.addEventListener("error", onUploadError, false);"POST", "UploadServlet");
    /* This function will continueously update the progress bar */
    function onUploadProgress(e) {
        if (e.lengthComputable) {
            var percentComplete = parseInt((e.loaded) * 100 / fileSize);
            var pbar = $('#progress-bar-'+fileUploadCount);
            var bar=pbar.find(".progress-bar");
            var sLoaded=pbar.find(".size-loaded");
            var pLoaded=pbar.find(".percent-loaded");
            bar.css("width",percentComplete + '%');
            sLoaded.html(parseFileSize(e.loaded)+ " / ");
            pLoaded.html("("+percentComplete+ "%)");
        } else {
            alert('unable to compute');
    /* This function will call when upload is completed */
    function onUploadComplete(e, error) {
        var pbar = $('#progress-bar-'+fileUploadCount);
            pbar.find(".size-loaded").html('<i class="fa fa-check text-success"></i> ');
        if (fileUploadCount < totalFileCount) {
            //ajax call if more files are there 
            $("#upload-header-text").html((fileUploadCount+1)+" of "+totalFileCount+" file(s) is uploading");
        } else {
            $("#upload-header-text").html("File(s) uploaded successfully!");
    /* This function will call when an error come while uploading */
    function onUploadError(e) {
        console.error("Something went wrong!");
    function showHide(ele){

Step-8. Configure Tomcat Server

In order to run the application in eclipse, a Server needs to be configured. To configure Tomcat Server you can follow the Configuration steps here.

Step-9. Run the Application

To Run the application, Right-click on Project(AdvFileUploadJava) > Run As > Run on Server as below image:

Java file upload ajax -project run on server
Java file upload ajax -run on server dialog

Now choose Tomcat v8.0 Server and click on the Finish button. After that access the below URL in any browser as below:

URL: http://localhost:8081/AdvFileUploadJava/filesupload.html ( make sure about your server port number )

Java file upload ajax - project running preview

That’s it you have created the application and successfully executed it.


In this article, you have seen the step-by-step guide for creating file upload with javascript ajax. You have also seen the bootstrap file upload progress bar for uploading multiple files at a time.

Hope you like this article!

Related Articles:

Share with friends

3 thoughts on “Java file upload with progress bar Ajax [Step-by-step]”

Leave a Comment

Your email address will not be published. Required fields are marked *