Enterprise Java

Ajax File Upload with Servlet and Bootstrap


In this tutorial, we will check how Ajax file upload works with Servlets. Also we will decorate our form with Bootstrap and ajaxify file upload through jQuery Ajax.


The basic servlet implementation is the same. So the first thing we need to do is update our web.xml file and specify servlets for our application.


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

Note that the welcome page specified is home.jsp. So when we run the servlet application, the application should find the welcome page jsp and the servlet class i.e. DemoFileUploadServlet.


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File Upload Example in JSP and Servlet - Java web application</title>
<link rel="stylesheet"
	$(document).ready(function() {
		function bs_input_file() {
				function() {
					if ( ! $(this).prev().hasClass('input-ghost') ) {
						var element = $("<input type='file' class='input-ghost' style='visibility:hidden; height:0'>");
						$(this).find('input').mousedown(function() {
							return false;
						return element;
		$("#uploadBtn").on("click", function() {
			var url = "demo";
			var form = $("#sampleUploadFrm")[0];
			var data = new FormData(form);
			/* var data = {};
			data['key1'] = 'value1';
			data['key2'] = 'value2'; */
				type : "POST",
				encType : "multipart/form-data",
				url : url,
				cache : false,
				processData : false,
				contentType : false,
				data : data,
				success : function(msg) {
					var response = JSON.parse(msg);
					var status = response.status;
					if (status == 1) {
						alert("File has been uploaded successfully");
					} else {
						alert("Couldn't upload file");
				error : function(msg) {
					alert("Couldn't upload file");
	<div class="container">
		<div class="col-md-8 col-md-offset-2">
			<h3>File Upload Example Using Servlet, Bootstrap and Ajax - jCombat</h3>
			<form id="sampleUploadFrm" method="POST" action="#" enctype="multipart/form-data">
				<!-- COMPONENT START -->
				<div class="form-group">
					<div class="input-group input-file" name="file">
						<span class="input-group-btn">
							<button class="btn btn-default btn-choose" type="button">Choose</button>
						</span> <input type="text" class="form-control"
							placeholder='Choose a file...' /> <span class="input-group-btn">
							<button class="btn btn-warning btn-reset" type="button">Reset</button>
				<!-- COMPONENT END -->
				<div class="form-group">
					<button type="button" class="btn btn-primary pull-right" id="uploadBtn">Submit</button>
					<button type="reset" class="btn btn-danger">Reset</button>

In home.jsp we have the HTML form for file upload, which uses Bootstrap. We also have the <script> tag added at the top, which has the jquery code to ajaxify the form submit action.

Next lets create the servlet class –


package com.jcombat.sample;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class DemoFileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
     * @see HttpServlet#HttpServlet()
    public DemoFileUploadServlet() {
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		final String UPLOAD_DIRECTORY = "C:/uploads";
			try {
                List multiparts = new ServletFileUpload(
                                         new DiskFileItemFactory()).parseRequest(request);
                for(FileItem item : multiparts){
                    	File fileSaveDir = new File(UPLOAD_DIRECTORY);
                    	if (!fileSaveDir.exists()) {
                        String name = new File(item.getName()).getName();
                        item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
			} catch (Exception e) {
				// exception handling
			PrintWriter out = response.getWriter();

Ensure the pom.xml file has the following dependencies added.


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<name>Servlet with Maven Demo</name>

Executing the application

When we execute the application, we see the below HTML form.


Choose the file and click on Submit. Once the file gets uploaded successfully, we get an alert saying – ‘File has been uploaded successfully’.


Download the source code

Download the source code

Published on Java Code Geeks with permission by Abhimanyu Prasad, partner at our JCG program. See the original article here: Ajax File Upload with Servlet and Bootstrap

Opinions expressed by Java Code Geeks contributors are their own.

Abhimanyu Prasad

Abhimanyu is a passionate tech blogger and senior programmer, who has an extensive end-to-end development experience with wide range of technologies. He is the founder and administrator at jCombat.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
5 years ago

Hi I need to exactly what is shown here, and this works, except I need it post additional form field data and retrieve it with response.getParameter() in the servlet. Currently all additional field values are null.

Back to top button