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
<?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"> <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
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <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" href="https://www.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://www.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9hamF4Lmdvb2dsZWFwaXMuY29tL2FqYXgvlibs/jquery/3.3.1/jquery.min.js"></script> <script src="https://www.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/3.3.7/js/bootstrap.min.js"></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
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
<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"> <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.
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
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. |
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.