Upload files to the server using jsp and servlet

  •  
  •  
  •  
  •  
  •  
  •  

Upload files to the server using JSP and servlet is a very easy and a common task in Java. The following example will give you a clear idea about how to upload files to the server using JSP and servlet. But before start coding, you need to know some important things. Like, “enctype=multipart/form-data“,  “HTTP POST“,  “apache commons” — what are these and why you need these? The enctype is an attribute that must be set within  “<form>” tag if you want to upload files to the server. The form method attribute should be set to POST. Upload files depend on the commons-fileupload and commons-io library so you must include these two files in the WEB-INF/lib folder.

Upload files to the server using jsp and servlet

This example consists of four following source files —

  • web.xml — This file defines and configures the url mapping
  • index.jsp — This is a jsp page which displays the upload form
  • message.jsp — This is a jsp page which displays the message after the file is uploaded
  • UploadFile.java — Java servlet that handles file upload to the server

web.xml (Web deployment descriptor)

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>uploading_file_using_jsp</display-name>
  
  <servlet>
    <display-name>UploadFile</display-name>
    <servlet-name>UploadFile</servlet-name>
    <servlet-class>com.upload.UploadFile</servlet-class>
  </servlet>
   
  <servlet-mapping>
    <servlet-name>UploadFile</servlet-name>
    <url-pattern>/upload-file</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

File upload form (index.jsp)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Upload files to the server using jsp and servlet</title>
</head>
<body>
  <form action="upload-file" method="post" enctype="multipart/form-data">
    <input type="file" name=upload_file" value="" multiple="true" />
    <input type="submit" name="submit_btn" value="Upload" />
  </form>
</body>
</html>

index.jsp file contained the file upload form, from where users can choose files and upload to the server.

File upload handler class (UploadFile.java)

package com.upload;

import java.io.File;
import java.io.IOException;
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 UploadFile extends HttpServlet {
  
  
  //Location of the folder
  private static final String UPLOAD_DIRECTORY = "d:/uploads";
  
  
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    //Checks if the form has 'enctype=multipart/form-data' attribute in it.
        if (!ServletFileUpload.isMultipartContent(request)) {
        	request.setAttribute("message", "Error: Form tag must has 'enctype=multipart/form-data' attribute");
        } else {
            //Creates the directory if it does not exist in the specified location
            File uploadDir = new File(UPLOAD_DIRECTORY);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            
            try {
              List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
              for(FileItem item : multiparts){
                  if(!item.isFormField()){
                      String name = new File(item.getName()).getName();
                      item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                  }
              }
              request.setAttribute("message", "File(s) uploaded successfully!");
            } catch(Exception e) {
            	request.setAttribute("message", "File(s) upload failed due to " + e.getMessage()+"!");
            }
        }
        getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
        return;
    }
}

UploadFile.java is a servlet which does the actual thing. This file is responsible for uploading files to the server.

Message page (message.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    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>Upload files to the server using jsp and servlet</title>
</head>
<body>
    <center>
        <h2>${message}</h2>
        <a href="./">Upload again</a>
    </center>
</body>
</html>

message.jsp displays the result after for being submitted. Whether files are uploaded or not to the server, it displays the corresponding message.

Dependency

To compile and run this java application in a web server like Tomcat, we need to add the following dependencies in the lib folder —

You can download the complete source code from the below download link and please like and share the tutorial link to others.

 

About Mitrajit

Leave a Reply

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

Prove you are a human *