Uploading and Downloading Files in Servlet

Uploading and Downloading Files in Servlet

In this article, I am going to discuss How to upload and upload files to the server in servlet. Please read our previous article where we discussed how to Improving Servlet performance to fetch records from the database. At the end of this article, you will understand how to set up the File Upload and File Download functionality in a Servlet based Java web application. As part of this example, we have created the following files:

  1. fileupload.jsp
  2. allfiles.jsp
  3. fileuploadResponse.jsp
  4. UploadDetail.java
  5. FileUploadServlet.java
  6. UploadedFileServlet.java
  7. FileDownloadServlet.java
  8. web.xml
  9. main.css

UploadDetail.java is a POJO class used to store the uploaded file status i.e., Filename, File Status, and File Upload Status. FileUploadServlet.java is a controller class used to upload a file. The servlet is annotated with the @Multipartconfig annotation with File Size Threshold, Maximum File Size, and Maximum Request Size. UploadedFileServlet.java is a controller class used to display the files which are already uploaded to the server. FileDownloadServlet.java is used to download the file from the server.

fileupload.jsp page contains the upload form to upload a single file or multiple files. FileUploadResponse.jsp page is used to display the result of the uploaded files. In this JSP, we iterate on the list of the uploadDetail objects and print the tabular data of the information of the uploaded file. Also, on this page, we have created the last column as a download link for the uploaded files. allfiles.jsp page is used to display the result for the total files that are residing on the server. web.xml is a deployment descriptor containing information about servlets. main.css is a style sheet used to describe the look and formatting of a document.

fileupload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
 <head>
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     <title>Servlet File Upload/Download</title> 
     <link rel="stylesheet" href="resource/css/main.css" />
 </head>
 <body>
     <div class="panel">
         <h1>File Upload</h1>
         <h3>Press 'CTRL' Key+Click On File To Select Multiple Files in Open Dialog</h3>
         <form id="fileUploadForm" method="post" action="fileUploadServlet" enctype="multipart/form-data">
             <div class="form_group">
                 <label>Upload File</label><span id="colon">: </span><input id="fileAttachment" type="file" name="fileUpload" multiple="multiple" />
                 <span id="fileUploadErr">Please Upload A File!</span>
             </div>
             <button id="uploadBtn" type="submit" class="btn btn_primary">Upload</button>
         </form>
     </div>
     
     <!-- List All Uploaded Files -->
     <div class="panel">
         <a id="allFiles" class="hyperLink" href="<%=request.getContextPath()%>/uploadedFilesServlet">List all uploaded files</a>
     </div>
 </body>
</html>
allfiles.jsp
<%@page import="java.util.List"%>
<%@page import="com.jcg.servlet.UploadDetail"%>
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">        
        <title>Servlet File Upload/Download</title>
        
        <link rel="stylesheet" href="resource/css/main.css" />
    </head>
    <body>
        <div class="panel">
            <h1>Uploaded Files</h1>
            <table class="bordered_table">
               <thead>
                  <tr align="center"><th>File Name</th><th>File Size</th><th>Action</th></tr>
               </thead>
               <tbody>
                  <% List<UploadDetail> uploadDetails = (List<UploadDetail>)request.getAttribute("uploadedFiles");
                     if(uploadDetails != null && uploadDetails.size() > 0) {
                     for(int i=0; i<uploadDetails.size(); i++) {
                  %>
                  <tr>
                     <td align="center"><span id="fileName"><%=uploadDetails.get(i).getFileName() %></span></td>
                     <td align="center"><span id="fileSize"><%=uploadDetails.get(i).getFileSize() %> KB</span></td>
                     <td align="center"><span id="fileDownload"><a id="downloadLink" class="hyperLink" href="<%=request.getContextPath()%>/downloadServlet?fileName=<%=uploadDetails.get(i).getFileName() %>">Download</a></span></td>
                  </tr>
                  <% }
                   } else { %>
                  <tr>
                     <td colspan="3" align="center"><span id="noFiles">No Files Uploaded.....!</span></td>
                  </tr>
                  <% } %>
               </tbody>
            </table>
            <div class="margin_top_15px">
               <a id="fileUpload" class="hyperLink" href="<%=request.getContextPath()%>/fileupload.jsp">Back</a>
            </div>
         </div>
     </body>
</html>
fileuploadResponse.jsp
<%@page import="java.util.List"%>
<%@page import="com.servlet.UploadDetail"%>
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">		
  <title>Servlet File Upload/Download</title>
  
  <link rel="stylesheet" href="resource/css/main.css" />
 </head>
 <body>
  <div class="panel">
   <h1>File Upload Status</h1>
      <table class="bordered_table">
      	<thead>
      		<tr align="center"><th>File Name</th><th>File Size</th><th>Upload Status</th><th>Action</th></tr>
      	</thead>
      	<tbody>
      		<% List<UploadDetail> uploadDetails = (List<UploadDetail>)request.getAttribute("uploadedFiles");
      			for(int i=0; i<uploadDetails.size(); i++) {
      	    %>
      	    <tr>
      	     	<td align="center"><span id="fileName"><%=uploadDetails.get(i).getFileName() %></span></td>
                     	<td align="center"><span id="fileSize"><%=uploadDetails.get(i).getFileSize() %> KB</span></td>
                  	 	<td align="center"><span id="fileuploadStatus"><%=uploadDetails.get(i).getUploadStatus() %></span></td>
                  	 	<td align="center"><span id="fileDownload"><a id="downloadLink" class="hyperLink" href="<%=request.getContextPath()%>/downloadServlet?fileName=<%=uploadDetails.get(i).getFileName() %>">Download</a></span></td>                		    	    	
      	    </tr>
      	    <% } %>
      	</tbody>
      </table>
      <div class="margin_top_15px">
      	<a id="fileUpload" class="hyperLink" href="<%=request.getContextPath()%>/fileupload.jsp">Back</a>
      </div>
  </div>
 </body>
</html>
UploadDetail.java
import java.io.Serializable;
public class UploadDetail implements Serializable {

 private long fileSize;
 private String fileName, uploadStatus;

 private static final long serialVersionUID = 1L;

 public long getFileSize() {
  return fileSize;
 }

 public void setFileSize(long fileSize) {
  this.fileSize = fileSize;
 }

 public String getFileName() {
  return fileName;
 }

 public void setFileName(String fileName) {
  this.fileName = fileName;
 }

 public String getUploadStatus() {
  return uploadStatus;
 }

 public void setUploadStatus(String uploadStatus) {
  this.uploadStatus = uploadStatus;
 }
}
FileUploadServlet.java
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
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;

@WebServlet(description = "Upload File To The Server", urlPatterns = { "/fileUploadServlet" })
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 10, maxFileSize = 1024 * 1024 * 30, maxRequestSize = 1024 * 1024 * 50)
public class FileUploadServlet extends HttpServlet {

 private static final long serialVersionUID = 1L;
 public static final String UPLOAD_DIR = "uploadedFiles";

 /***** This Method Is Called By The Servlet Container To Process A 'POST' Request *****/
 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  handleRequest(request, response);
 }

 public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  /***** Get The Absolute Path Of The Web Application *****/
  String applicationPath = getServletContext().getRealPath(""),
    uploadPath = applicationPath + File.separator + UPLOAD_DIR;

  File fileUploadDirectory = new File(uploadPath);
  if (!fileUploadDirectory.exists()) {
   fileUploadDirectory.mkdirs();
  }

  String fileName = "";
  UploadDetail details = null;
  List<UploadDetail> fileList = new ArrayList<UploadDetail>();

  for (Part part : request.getParts()) {
   fileName = extractFileName(part);
   details = new UploadDetail();
   details.setFileName(fileName);
   details.setFileSize(part.getSize() / 1024);
   try {
    part.write(uploadPath + File.separator + fileName);
    details.setUploadStatus("Success");
   } catch (IOException ioObj) {
    details.setUploadStatus("Failure : "+ ioObj.getMessage());
   }
   fileList.add(details);
  }

  request.setAttribute("uploadedFiles", fileList);
  RequestDispatcher dispatcher = request.getRequestDispatcher("/fileuploadResponse.jsp");
  dispatcher.forward(request, response);
 }

 /***** Helper Method #1 - This Method Is Used To Read The File Names *****/
 private String extractFileName(Part part) {
  String fileName = "", 
    contentDisposition = part.getHeader("content-disposition");
  String[] items = contentDisposition.split(";");
  for (String item : items) {
   if (item.trim().startsWith("filename")) {
    fileName = item.substring(item.indexOf("=") + 2, item.length() - 1);
   }
  }
  return fileName;
 }
UploadedFileServlet.java
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(description = "List The Already Uploaded Files", urlPatterns = { "/uploadedFilesServlet" })
public class UploadedFilesServlet extends HttpServlet {

 private static final long serialVersionUID = 1L;
 public static final String UPLOAD_DIR = "uploadedFiles";

 /***** This Method Is Called By The Servlet Container To Process A 'GET' Request *****/
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  handleRequest(request, response);
 }

 public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  /***** Get The Absolute Path Of The Web Application *****/
  String applicationPath = getServletContext().getRealPath(""),
    uploadPath = applicationPath + File.separator + UPLOAD_DIR;

  File fileUploadDirectory = new File(uploadPath);
  if (!fileUploadDirectory.exists()) {
   fileUploadDirectory.mkdirs();
  }

  UploadDetail details = null;
  File[] allFiles = fileUploadDirectory.listFiles();
  List<UploadDetail> fileList = new ArrayList<UploadDetail>();		

  for (File file : allFiles) {
   details = new UploadDetail();
   details.setFileName(file.getName());
   details.setFileSize(file.length() / 1024);
   fileList.add(details);
  }

  request.setAttribute("uploadedFiles", fileList);
  RequestDispatcher dispatcher = request.getRequestDispatcher("/allfiles.jsp");
  dispatcher.forward(request, response);
 }
}
FileDownloadServlet.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(description = "Download File From The Server", urlPatterns = { "/downloadServlet" })
public class FileDownloadServlet extends HttpServlet {

 private static final long serialVersionUID = 1L;

 public static int BUFFER_SIZE = 1024 * 100;
 public static final String UPLOAD_DIR = "uploadedFiles";

 /***** This Method Is Called By The Servlet Container To Process A 'GET' Request *****/
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  handleRequest(request, response);
 }

 public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  /***** Get The Absolute Path Of The File To Be Downloaded *****/
  String fileName = request.getParameter("fileName"),
    applicationPath = getServletContext().getRealPath(""),
    downloadPath = applicationPath + File.separator + UPLOAD_DIR,
    filePath = downloadPath + File.separator + fileName;

  File file = new File(filePath);
  OutputStream outStream = null;
  FileInputStream inputStream = null;

  if (file.exists()) {

   /**** Setting The Content Attributes For The Response Object ****/
   String mimeType = "application/octet-stream";
   response.setContentType(mimeType);

   /**** Setting The Headers For The Response Object ****/
   String headerKey = "Content-Disposition";
   String headerValue = String.format("attachment; filename=\"%s\"", file.getName());
   response.setHeader(headerKey, headerValue);

   try {

    /**** Get The Output Stream Of The Response ****/
    outStream = response.getOutputStream();
    inputStream = new FileInputStream(file);
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;

    /**** Write Each Byte Of Data Read From The Input Stream Write Each Byte Of Data  Read From The Input Stream Into The Output Stream ****/
    while ((bytesRead = inputStream.read(buffer)) != -1) {
     outStream.write(buffer, 0, bytesRead);
    }				
   } catch(IOException ioExObj) {
    System.out.println("Exception While Performing The I/O Operation?= " + ioExObj.getMessage());
   } finally {				
    if (inputStream != null) {
     inputStream.close();
    }

    outStream.flush();
    if (outStream != null) {
     outStream.close();
    }
   }
  } else {

   /***** Set Response Content Type *****/
   response.setContentType("text/html");

   /***** Print The Response *****/
   response.getWriter().println("<h3>File "+ fileName +" Is Not Present .....!</h3>");
  }
 }
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
   <display-name>Servlet File Upload/Download</display-name>
   <welcome-file-list>
      <welcome-file>fileupload.jsp</welcome-file>
   </welcome-file-list>
</web-app>
main.css
* {
 box-sizing: border-box;
}

.margin_top_15px {
 margin-top: 15px;
}

.panel {
 display: block;
 padding: 15px;
 border: 1px solid #c0c0c0;
 width: 849px;
 margin: 52px 0px 0px 32px;
}

label {
 display: inline-block;
 margin-bottom: 5px;
}

.form_group {
 margin: 10px;
}

.btn_primary {
 color: #fff;
 background-color: #0275d8;
 border-color: #0275d8;
}

.btn {
 display: inline-block;
 padding: 10px;
 text-align: center;
 white-space: nowrap;
 vertical-align: middle;
 cursor: pointer;
 border: 1px solid transparent;
}

.input_error {
 color: #DE3330;
 padding: 5px;
}

.bordered_table {
 border-collapse: collapse;
 width: 100%;
 table-layout: fixed;
}

.bordered_table tr,th,td {
 border: 1px solid #333;
}

.bordered_table th,td {
 padding: 5px;
}

.bordered_table td {
 word-wrap: break-word;
}

#noFiles {
 color: red;
 font-size: larger;
}

.hyperLink {
 text-decoration: none;
 cursor: pointer;
}
Output

Run your code to get the following output. Click on “Choose file”, select a file to upload, and click on the “Upload” button. Click on the “List all uploaded Files” link to see the list of already uploaded files.

How to upload and upload files to the server in servlet

After clicking on the “Upload” button you will get the following response. Press the “Back” link to go back to the File Upload page.

Uploading and Downloading Files in Servlet

After clicking on the “List all uploaded files” link you will get the following response. Click on the “Download” link to download the particular file.

Uploading Files in Servlet

After downloading the particular file, you will find the file in This PC -> Downloads option.

Downloading Files in Servlet

In the next article, I am going to discuss How to send email through JavaMail API in Servlet. Here, in this article, we develop an application to upload and upload files to the server in servlet and I hope you enjoy this How to upload and upload files to the server in servlet article.

Leave a Reply

Your email address will not be published.