Enterprise Java

Ajax File Upload with Servlet and Bootstrap

Introduction

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.

Implementation

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.

web.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="UTF-8"?>
  <display-name>DemoFileUploadServlet</display-name>
  <welcome-file-list>
    <welcome-file>home.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>DemoFileUploadServlet</display-name>
    <servlet-name>demo</servlet-name>
    <servlet-class>com.jcombat.sample.DemoFileUploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>demo</servlet-name>
    <url-pattern>/demo</url-pattern>
  </servlet-mapping>
</web-app>

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.

home.jsp

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<html>
<head>
<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"
<script
<script
<script>
    $(document).ready(function() {
        function bs_input_file() {
            $(".input-file").before(
                function() {
                    if ( ! $(this).prev().hasClass('input-ghost') ) {
                        var element = $("<input type='file' class='input-ghost' style='visibility:hidden; height:0'>");
                        element.attr("name",$(this).attr("name"));
                        element.change(function(){
                            element.next(element).find('input').val((element.val()).split('\\').pop());
                        });
                        $(this).find("button.btn-choose").click(function(){
                            element.click();
                        });
                        $(this).find("button.btn-reset").click(function(){
                            element.val(null);
                            $(this).parents(".input-file").find('input').val('');
                        });
                        $(this).find('input').css("cursor","pointer");
                        $(this).find('input').mousedown(function() {
                            $(this).parents('.input-file').prev().click();
                            return false;
                        });
                        return element;
                    }
                }
            );
        }
         
        bs_input_file();
         
        $("#uploadBtn").on("click", function() {
            var url = "demo";
            var form = $("#sampleUploadFrm")[0];
            var data = new FormData(form);
            /* var data = {};
            data['key1'] = 'value1';
            data['key2'] = 'value2'; */
            $.ajax({
                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");
                }
            });
        });
    });
</script>
</head>
  
<body>
    <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>
                        </span>
                    </div>
                </div>
                <!-- 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>
                </div>
            </form>
        </div>
    </div>
</body>
</html>

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 –

DemoFileUploadServlet.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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() {
        super();
    }
  
    /**
     * @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";
        if(ServletFileUpload.isMultipartContent(request)){
            try {
                List multiparts = new ServletFileUpload(
                                         new DiskFileItemFactory()).parseRequest(request);
                for(FileItem item : multiparts){
                    if(!item.isFormField()){
                        File fileSaveDir = new File(UPLOAD_DIRECTORY);
                        if (!fileSaveDir.exists()) {
                            fileSaveDir.mkdir();
                        }
                        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();
            out.print("{\"status\":1}");
        }
         
    }
  
}

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

pom.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.jcombat.sample</groupId>
    <artifactId>ServletFileUploadDemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>Servlet with Maven Demo</name>
  
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>
    </dependencies>
  
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Executing the application

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

Bootstrap

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

Bootstrap

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.
Subscribe
Notify of
guest


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

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Julian
Julian
6 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