Friday, June 4, 2010

Introducing FileUpload

The FileUpload component has the capability of simplifying the handling of files uploaded to a server. Note that the FileUpload component is meant for use on the server side; in other words, it handles where the files are being uploaded to—not the client side where the files are uploaded from. Uploading files from an HTML form is pretty simple; however, handling these files when they get to the server is not that simple. If you want to apply any rules and store these files based on those rules, things get more difficult.

The FileUpload component remedies this situation, and in very few lines of code you can easily manage the files uploaded and store them in appropriate locations. You will now see an example where you upload some files first using a standard HTML form and then using HttpClient code.

Using HTML File Upload
The commonly used methodology to upload files is to have an HTML form where you define the files you want to upload. A common example of this HTML interface is the Web page you encounter when you want to attach files to an email while using any of the popular Web mail services.

In this example, you will create a simple HTML page where you provide for three files to be uploaded. Listing 9-4 shows the HTML for this page. Note that the enctype attribute for the form has the value multipart/form-data, and the input tag used is of type file. Based on the value of the action attribute, on form submission, the data is sent to ProcessFileUpload.jsp.

Listing 9-4. UploadFiles.html



File Upload Page

Upload Files
File 1:

File 2:

File 3:




You can use a servlet to handle the file upload. I have used JSP to minimize the code you need to write. The task that the JSP has to accomplish is to pick up the files that are sent as part of the request and store these files on the server. In the JSP, instead of displaying the result of the upload in the Web browser, I have chosen to print messages on the server console so that you can use this same JSP when it is not invoked through an HTML form but by using HttpClient-based code.

Listing 9-5 shows the JSP code. Note the code that checks whether the item is a form field. This check is required because the Submit button contents are also sent as part of the request, and you want to distinguish between this data and the files that are part of the request. You have set the maximum file size to 1,000,000 bytes using the setSizeMax method.

Listing 9-5. ProcessFileUpload.jsp
<%@ page contentType="text/html;charset=windows-1252"%>
<%@ page import="org.apache.commons.fileupload.DiskFileUpload"%>
<%@ page import="org.apache.commons.fileupload.FileItem"%>
<%@ page import="java.util.List"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.io.File"%>
html>


Process File Upload

<% System.out.println("Content Type ="+request.getContentType()); DiskFileUpload fu = new DiskFileUpload(); // If file size exceeds, a FileUploadException will be thrown fu.setSizeMax(1000000); List fileItems = fu.parseRequest(request); Iterator itr = fileItems.iterator(); while(itr.hasNext()) { FileItem fi = (FileItem)itr.next(); //Check if not form field so as to only handle the file inputs //else condition handles the submit button input if(!fi.isFormField()) { System.out.println("nNAME: "+fi.getName()); System.out.println("SIZE: "+fi.getSize()); //System.out.println(fi.getOutputStream().toString()); File fNew= new File(application.getRealPath("/"), fi.getName()); System.out.println(fNew.getAbsolutePath()); fi.write(fNew); } else { System.out.println("Field ="+fi.getFieldName()); } } %>

Upload Successful!!


CAUTION With FileUpload 1.0 I found that when the form was submitted using Opera version 7.11, the getName method of the class FileItem returns just the name of the file. However, if the form is submitted using Internet Explorer 5.5, the filename along with its entire path is returned by the same method. This can cause some problems.

To run this example, you can use any three files, as the contents of the files are not important. Upon submitting the form using Opera and uploading three random XML files, the output I got on the Tomcat server console was as follows:

Content Type =multipart/form-data; boundary=----------rz7ZNYDVpN1To8L73sZ6OE

NAME: academy.xml
SIZE: 951
D:javaGizmosjakarta-tomcat-4.0.1webappsHttpServerSideAppacademy.xml

NAME: academyRules.xml
SIZE: 1211
D:javaGizmosjakarta-tomcat-4.0.1webappsHttpServerSideAppacademyRules.xml

NAME: students.xml
SIZE: 279
D:javaGizmosjakarta-tomcat-4.0.1webappsHttpServerSideAppstudents.xml
Field =Submit
However, when submitting this same form using Internet Explorer 5.5, the output on the server console was as follows:
Content Type =multipart/form-data; boundary=---------------------------7d3bb1de0
2e4

NAME: D:tempacademy.xml
SIZE: 951
D:javaGizmosjakarta-tomcat-4.0.1webappsHttpServerSideAppD:tempacademy.xml
The browser displayed the following message: “The requested resource (D:javaGizmosjakarta-tomcat-4.0.1webappsHttpServerSideAppD:tempacademy.xml (The filename, directory name, or volume label syntax is incorrect)) is not available.”

This contrasting behavior on different browsers can cause problems. One workaround that I found in an article at http://www.onjava.com/pub/a/onjava/2003/06/25/commons.html is to first create a file reference with whatever is supplied by the getName method and then create a new file reference using the name returned by the earlier file reference. Therefore, you can insert the following code to have your code work with both browsers (I wonder who the guilty party is…blaming Microsoft is always the easy way out)

File tempFileRef = new File(fi.getName());
File fNew = new File(application.getRealPath("/"),tempFileRef.getName());
In this section, you uploaded files using a standard HTML form mechanism. However, often a need arises to be able to upload files from within your Java code, without any browser or form coming into the picture. In the next section, you will look at HttpClient-based file upload.

Using HttpClient-Based FileUpload
Earlier in the article you saw some of the capabilities of the HttpClient component. One capability I did not cover was its ability to send multipart requests. In this section, you will use this capability to upload a few files to the same JSP that you used for uploads using HTML.

The class org.apache.commons.httpclient.methods.MultipartPostMethod provides the multipart method capability to send multipart-encoded forms, and the package org.apache.commons.httpclient.methods.multipart has the support classes required. Sending a multipart form using HttpClient is quite simple. In the code in Listing 9-6, you send three files to ProcessFileUpload.jsp.

Listing 9-6. HttpMultiPartFileUpload.java
package com.commonsbook.chap9;
import java.io.File;
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.MultipartPostMethod;

public class HttpMultiPartFileUpload {
private static String url =
"http://localhost:8080/HttpServerSideApp/ProcessFileUpload.jsp";

public static void main(String[] args) throws IOException {
HttpClient client = new HttpClient();
MultipartPostMethod mPost = new MultipartPostMethod(url);
client.setConnectionTimeout(8000);

// Send any XML file as the body of the POST request
File f1 = new File("students.xml");
File f2 = new File("academy.xml");
File f3 = new File("academyRules.xml");

System.out.println("File1 Length = " + f1.length());
System.out.println("File2 Length = " + f2.length());
System.out.println("File3 Length = " + f3.length());

mPost.addParameter(f1.getName(), f1);
mPost.addParameter(f2.getName(), f2);
mPost.addParameter(f3.getName(), f3);

int statusCode1 = client.executeMethod(mPost);

System.out.println("statusLine>>>" + mPost.getStatusLine());
mPost.releaseConnection();
}
}
In this code, you just add the files as parameters and execute the method. The ProcessFileUpload.jsp file gets invoked, and the output is as follows:

Content Type =multipart/form-data; boundary=----------------31415926535897932384
6

NAME: students.xml
SIZE: 279
D:javaGizmosjakarta-tomcat-4.0.1webappsHttpServerSideAppstudents.xml

NAME: academy.xml
SIZE: 951
D:javaGizmosjakarta-tomcat-4.0.1webappsHttpServerSideAppacademy.xml

NAME: academyRules.xml
SIZE: 1211
D:javaGizmosjakarta-tomcat-4.0.1webappsHttpServerSideAppacademyRules.xml
Thus, file uploads on the server side become quite a simple task if you are using the Commons FileUpload component.

Summary
In this article, you saw the HttpClient and FileUpload components. Although HttpClient can be useful in any kind of applications that use HTTP for communication, the FileUpload component has a much more specific scope. One important plus for HttpClient is the existence of a decent user guide and tutorial. The FileUpload component can be just what you are looking for if you are wondering what to use and how to manage files uploaded through your application.

No comments: