Wednesday, April 9, 2008

Form-based File Upload with Java Servlet or JSP

To upload files using a web form displayed in the browser to the target website, we use a special type of form called the Multipart form, it is the web server's capability
to handle multipart data, when using PHP you have built-in options, however when using Java based web server like Tomcat as in this illustration, you have to depend on 3rd party libraries, there are several providers, some charge a fee and some are free, in this article we will make use of libraries provided by Apache themselves.

"Apache Jakarta Commons FileUpload package "

It is open-source and can be downloaded free of charge over the Internet. We will demonstrate how to use the Apache Jakarta Commons FileUpload package to extract uploaded files submitted from a form. The techniques are the same for HTML and XHTML. If you are not familiar with JSP or Java Servlet we advise a primer course first, It is assumed the reader is comfortable using JSP and has adequate knowledge of servlets and knows how to deploy them atleast on apache tomcat.

In this article we'll use Commons FileUpload 1.1.1, later versions may have some changes.

Step 1 : Get the Libraries
To download the Apache Jakarta Commons FileUpload library, go to the home page of the "Apache Jakarta Commons FileUpload Project"
(http://jakarta.apache.org/commons/fileupload/), You will also need
"Commons IO library" (http://jakarta.apache.org/commons/io/)

Step 2 : Install the Apache Jakarta Commons FileUpload and the Commons IO libraries.

Installation is simply to copy the JAR files "commons-fileupload-1.1.1.jar" and "commons-io-1.2.jar" to the /WEB-INF/lib/ directory in the document root of your web application.

Note that JAR libraries stored in /WEB-INF/lib/ will be available to the containing web application only. If you want to share the libraries among all web applications installed in Tomcat (suppose you are using Tomcat 5 or Tomcat 4), the JAR files should be copied to the $CATALINA_HOME/shared/lib/ directory, where $CATALINA_HOME is the root of your Tomcat installation.

Step 3 : Create a HTML page which has a multipart form

form.html
~~~~~~~~
<form action="upload.jsp" method="post" enctype="multipart/form-data">

<input name="file" type="file">

<input type="submit">

</form>




Step 4 : Write the code for upload.jsp

<%@

page
import="org.apache.commons.fileupload.*,org.apache.commons.fileupload.servlet.ServletFileUpload,

org.apache.commons.fileupload.disk.DiskFileItemFactory,
org.apache.commons.io.FilenameUtils, java.util.*, java.io.File,

java.lang.Exception"

%>

<%
response.setContentType("application/vnd.wap.xhtml+xml");
%>

<html>

<head>
<title>File Upload
Example</title>
</head>


<body>
<h1>Data Received at the
Server</h1>
<hr/>

<p>

<%
if(ServletFileUpload.isMultipartContent(request)){

ServletFileUpload servletFileUpload = new ServletFileUpload(new


DiskFileItemFactory());


List fileItemsList = servletFileUpload.parseRequest(request);



String optionalFileName = "";


FileItem fileItem = null;



Iterator it = fileItemsList.iterator();


while(it.hasNext()){


FileItem fileItemTemp =(FileItem)it.next();


if(fileItemTemp.isFormField()){

%>

<b>Name-value
Pair Info:</b><br/>

Field
name:<%=fileItemTemp.getFieldName() %><br/>

Field
value: <%=fileItemTemp.getString()
%><br/><br/>

<%if(fileItemTemp.getFieldName().equals("filename")){

optionalFileName= fileItemTemp.getString();


}


else{


fileItem=fileItemTemp;


}



if(fileItem!=null){


String fileName = fileItem.getName();

%>

<b>Uploaded
File Info:</b><br/>

Content
type:<%=fileItem.getContentType() %>
<br/>
Field
name: <%=fileItem.getFieldName() %><br/>

File
name: <%=fileName %><br/>

File
size: <%=fileItem.getSize()%>
<br/><br/>

<%

/*Save the uploaded file if its size is greater than 0. */


if(fileItem.getSize()> 0){


if(optionalFileName.trim().equals("")){


fileName=FilenameUtils.getName(fileName);


}


else{


fileName=optionalFileName;


}



String dirName ="/file_uploads/";


File saveTo = new File(dirName + fileName);


try {


fileItem.write(saveTo);


%>

<b>The
uploaded file has been saved successfully.</b>


<%

}
catch(Exception
e){%>


<b>An
error occurred when we tried to save the uploaded
file.</b>


<%

}


}


}

}
%>


</p>
</body>
</html>




Step 5 : Test the application.

Start tomcat and invoke the form.html

http://localhost:8080/testing/form.html


Once you select a file and click submit
You should see a result page as follows




For more information you may visit this website
http://www.developershome.com/