Java Servlet File Upload

By | | Updated : 2021-03-12 | Viewed : 1533 times

This current tutorial is file uploading with the servlet. You can find a neat example here with an explanation.

Java Servlet File Upload

Perquisitions

  • JdK 11

  • Servlet 4.0

  • Apache-Tomcat 9.0.16

  • Eclipse 4.X

  • Apache Maven 3.X

Create Maven project for FileUploadApp-Example
Click on File tab 
--> New 
--> Click on Maven Project 
--> Please check on Create Simple Project (Skip architype selection) 
--> Click on Next --> Enter the values com.docsconsole.tutorials.servlet4 as Group Id, FileDownloadApp-Example as Artifact Id 
--> Click on Finish
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.docsconsole.servlet4.tutorials</groupId>
  <artifactId>FileUploadApp-Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>FileUploadApp-Example</name>
  <description>FileUploadApp-Example</description>
  
  <properties>
		<maven.war.plugin.version>3.2.2</maven.war.plugin.version>
		<servlets.version>4.0.0</servlets.version>
		<jsp.version>2.3.1</jsp.version>
		<jstl.version>1.2.2</jstl.version>
		<tld.version>1.1.2</tld.version>
		<log4j.version>1.2.17</log4j.version>
		<maven.compiler.source>11</maven.compiler.source>
		<maven.compiler.target>11</maven.compiler.target>
	</properties>

	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlets.version}</version>
			<scope>provided</scope>
		</dependency>

		<!-- JSP Dependency -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>${jsp.version}</version>
			<scope>provided</scope>
		</dependency>

		<!-- JSTL Dependency -->
		<dependency>
			<groupId>javax.servlet.jsp.jstl</groupId>
			<artifactId>javax.servlet.jsp.jstl-api</artifactId>
			<version>${jstl.version}</version>
		</dependency>
        <!-- Taglibs-->
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>${tld.version}</version>
		</dependency>
		<!-- Log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		<!-- Commons FileUpload component -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
	</dependencies>

	<build>
		<pluginManagement>
			<plugins>

				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-war-plugin</artifactId>
					<version>${maven.war.plugin.version}</version>
					<configuration>
						<warSourceDirectory>src/main/webapp</warSourceDirectory>
						<warName>${project.artifactId}</warName>
						<failOnMissingWebXml>false</failOnMissingWebXml>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>

Please create the Java and XML code files as given below.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>FileUploadApp-Example</display-name>
	<servlet>
		<servlet-name>FileUploadServlet</servlet-name>
		<servlet-class>com.docsconsole.servelet.tutorials.FileUploadServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>FileUploadServlet</servlet-name>
		<url-pattern>/fileUpload</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>home.jsp</welcome-file>
	</welcome-file-list>
</web-app>
FileUploadServlet.java
package com.docsconsole.servelet.tutorials;

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 FileUploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private final String UPLOAD_DIRECTORY = "D:/UploadDir";

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		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", "succeeded");
		} catch (Exception ex) {
			request.setAttribute("message", "failed");
		}

		request.getRequestDispatcher("/status.jsp").forward(request, response);

	}

}
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>FileUploadApp Example</title>
    </head>
  
    <body> 
        <div>
            <h3> Choose File to Upload: </h3>
            <form action="fileUpload" method="post" enctype="multipart/form-data">
                <input type="file" name="file" />
                <input type="submit" value="upload" />
            </form>          
        </div>
       
    </body>
</html>
status.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>
    </head>
  
    <body> 
        <div id="result">
         	<h3 style="color: #11d9e3;">File Uploading is succeeded</h3>
        </div>
       
    </body>
</html>

The final architecture of project is as given below.

Java Servlet File Upload

We programmed uploading directory D:/UploadDir. It should be there in your local system. Change it if it is required as per your machine.

Java Servlet File Upload
Java Servlet File Upload

Please test the application after deploying the application. File will be uploaded as shown above. URL: http://localhost:8080/FileUploadApp-Example/

Please refer to the Github repository here Servlet-FileUpload-Example-App

Leave A Reply