Using Apache Commons File Upload with Codenvy

The Commons File Upload package makes it easy to add robust, high-performance, file upload capability to your servlets and web applications.

Create a Project

Login to your Codenvy workspace and create a New WAR Project say “apacheFileUpload”. Project file structure is shown below:
project_structure

Create pom.xml file

Specify the below dependencies in pom.xml which are prerequisite for the File Upload implementation. Make sure these jars are included under Maven Dependencies.

  • Commons-fileupload-1.3.jar
  • Junit-4.8.1.jar
  • Javaee-web-api-6.0.jar
  • Commons-io-2.4.jar

pom.xml file

<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.codenvy</groupId>
<artifactId>apacheFileUpload</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>apacheFileUpload</name>

<dependencies>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

</dependencies>

<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Maven Repository Switchboard</name>
<url>http://repo1.maven.org/maven2</url>
</repository>
<repository>
<id>java.net2</id>
<name>Repository hosting the jee6 artifacts</name>
<url>http://download.java.net/maven/2</url>
</repository>
</repositories>

<build>
<finalName>apacheFileUpload</finalName>
</build>
</project>

Create FileUploadServlet class

This is a servlet class handles and parses the uploaded file and saves the file in the specified location.

package com.codenvy;

import java.io.File;
import java.io.IOException;
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;

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 static final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
	private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
	private static final int REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
	private List<FileItem> fileItem = null;
	private String __filePath = this.getClass().getClassLoader().getResource("../../").getFile();

	protected List<FileItem> initRequest(HttpServletRequest req) {
		boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		if(!isMultipart) throw new UnsupportedOperationException();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(THRESHOLD_SIZE);
		factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setFileSizeMax(MAX_FILE_SIZE);
		upload.setSizeMax(REQUEST_SIZE);
		List<FileItem> formItems = null;
		try {
			formItems = upload.parseRequest(req);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return formItems;
	}

	protected String getFieldValue(List<FileItem> formItems, String fieldName)
	{
		String value = null;
		try {
			for(FileItem fi : formItems )
			{
				if (fi.isFormField())
				{
					if(fi.getFieldName().equals(fieldName))
					{
						value = fi.getString();
					}
				}
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
		return value;
	}

	protected File uploadFile(List<FileItem> formItems, String destFolder)
	{
		String uploadPath = __filePath+destFolder;
		File uploadDir = new File(uploadPath);
		System.out.println(uploadDir.getAbsolutePath());
		if (!uploadDir.exists()) {
			uploadDir.mkdir();
		}
		File uploadedFile = null;
		try {
			for(FileItem fi : formItems ){
				if (!fi.isFormField()) {
					String fileName = new File(fi.getName()).getName();
					String filePath = uploadPath + File.separator + fileName;
					uploadedFile = new File(filePath);
					fi.write(uploadedFile);
				}
			}
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
		return uploadedFile;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException
	{
		fileItem = initRequest(request);
		String description = getFieldValue(fileItem, "inputDescription");
		File file = uploadFile(fileItem, "uploads");
  request.setAttribute("path",file.getAbsolutePath());

		request.setAttribute("description", description);
		RequestDispatcher rd = request.getRequestDispatcher("/success.jsp");
		rd.forward(request, response);
	}
}

Create index.jsp

Index jsp acts a an interface to browse the respective file form the local machine with some description and uploads.

<%@ 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>Apache Commons File Upload</title>
<link rel="stylesheet" href="css/style.css" type="text/css" />
</head>
<body>
<div class="upload">
<form action="upload" method="post" enctype="multipart/form-data">
<table width="358" border="0" cellspacing="0" cellpadding="0" class="table">
<center><p>Apache Commons File Upload</p>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td width="144"><strong>Description</strong></td>
<td width="8">&nbsp;</td>

<td width="203"><label>
<input type="text" name="inputDescription" />
</label></td>
</tr>
<tr>
<td><strong>Upload</strong></td>
<td>&nbsp;</td>
<td>
<input type="file" name="inputFile" /></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><label>
<input type="submit" name="Submit" value="Upload File"  class="button"/>
</label></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</table>
</form>
</div>

</body>
</html>

Create web.xml and success.jsp

We are mapping the index.jsp file to the earlier created servlet in this web.xml file and the action will load the success.jsp file :
Web.xml:

<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Web Application Created With eXo IDE</display-name>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>
<display-name>upload</display-name>
<servlet-name>upload</servlet-name>
<servlet-class>com.codenvy.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>

</web-app>

Build and Run the application

Upon successful building the application and executing, it loads index.jsp where we select the file and upload, then it will be successfully uploads to the location specified on the success.jsp file.