Archive for July, 2008
How to upload a file in Web application ?
Hello World !
Many would have encountered a situation where File upload is an add-on part to any wide & extensive web application. So don’t panic as soon as you get an requirement for File Upload as your task.
Let me quickly take you through the details of the File upload. To start with there are no particular API’s in java jdk for File Upload. So we depend on third party API’s and to list them there are many. I would like to cover only two ways of achieving it (ofcourse as usual with sample code).
1. MultipartRequest (com.oreilly.servlet.MultipartRequest) – A utility class from oreilly that supports file upload.
2. Apache Commons File Upload – a open source package from apache exclusively for file upload.So lets explore one by one,1. MultiPartRequest:
Its an special purpose utility class to handle file upload. There are few steps to be followed to achieve File upload using this utility.
Step 1:
In the form tag of your jsp/html file set the enctype attribute as below.
<form name=”uploadForm” method=”post” enctype=”multipart/form-data” > As many might be aware every Form attribute has a content-type that a userAgent can support.
Default content-type of the form is “application/x-www-form-urlencoded” Reference: W3.org
Step 2: So once you set the form enctype include the file upload component as mentioned below.<input type=”file” name=”attachment”/>
So with this two steps you are good to go with the UI.
Step 3: Once the UI is ready, next part is your request processor. It can be a java servlet or an Action Class in case of Struts. First you need to identify whether the request object received is an Multipart. So here is the code to do that.
boolean isMultiPart = MultiPartUtil.getInstance().isMultipart(request); //remember MultiPartUtil is my own helper class
Step 4: Once the request is identified as MultiPart, no longer you can retrieve the fields using request.getAttribute(). So here is the code to retrieve the field attributes of MultiPartRequest.
if (isMultipart) {
MultipartRequest multiPartRequest = MultipartUtil.getInstance().getMultipartRequest(request);
System.out.println(multiPartRequest.getParameter("candidateName"));//normal text field in html
System.out.println(multiPartRequest.getParameter(“candidate No:”));//normal text field in html
//below code for dealing with attachment file
File originalFile = null;
FileInputStream fisOriginal = null;
String uploadFileName = null;</code></span></span></span></span></span>
if(multiPartRequest.getFile("attachment")!= null){//attachment is the file upload control on html
originalFile = multiPartRequest.getFile("attachment"); //returns a file object of the file choosen
}
if(originalFile != null){//upload file exists
fisOriginal = new FileInputStream(originalFile);
uploadFileName = originalFile.getName();
}
So with the value of fisOriginal now you are good to write the FileInputStream to an blob column in db table or you can perform any file operation with that.
Step 5: Stttttttttooooooooopppppppppp. So where exactly the file is uploaded for my application to use/process it?. Good question , and here comes the complete code of my helper class.
public class MultipartUtil {
private static final MultipartUtil INSTANCE = new MultipartUtil();// as usual this is singleton</code>
public static MultipartUtil getInstance() {
return INSTANCE;
}
public boolean isMultipartRequest(HttpServletRequest request) {//to find is request object Multipart
String contentType = request.getContentType();
return (contentType != null && contentType.startsWith("multipart/form-data"))?true:false;
}
private MultipartRequest multiPart = null;
public MultipartRequest getMultipartRequest(HttpServletRequest request)
throws IOException {
if (multiPart == null) {
String dir = FileUploadUtil.getUploadDir(); //this gives the directory on your server say eg:/logs/upload to upload the file
if (dir == null){
dir = FileUploadUtil.getCurrentDirectoy();
}
multiPart = new MultipartRequest(request, dir);//create MultipartRequest object from Oreilly API
} else
return multiPart;
return multiPart;
}
public void resetMultipart() { // nullify the multipart request
multiPart = null;
}
}
Summary:
This doesn’t look neat isn’t it. See the bulkness of the code its too heavy. But still a good way of knowing the basics of File Upload. So remeber this is the base for any file upload technology.
2.Apache Commons File Upload:
For every tough or frequently used API’s there is an apache commons readily available. So you have Apache commons File upload . I am about to describe you how to achieve the same file upload using commons.
Lets dive into the sample code i have ,
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException { </code>
boolean isMultiPart= ServletFileUpload.isMultipartContent(req); // find the request object enctype
String uploadDirectory="c:/upload"; // location to upload the file
FileItemFactory fileFactory = new DiskFileItemFactory(100,new File(uploadDirectory)); //100 is the bytes to hold in memory beyond which write the file to the directory mentioned.
ServletFileUpload serFileUpload = new ServletFileUpload(fileFactory); //commons API to handle multipart encoding type
try {
List fileItems = serFileUpload.parseRequest(req);
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) { // identifies the normal form field , false when it identifies the upload field
//simply process the form fields
System.out.println("Text Value -->"+item.getString());
} else {
try {
String fileName= null;
if(item.getName() != null){
fileName=FilenameUtils.getName(item.getName());//FilenameUtils - commons.io API
item.write(new File(uploadDirectory+File.separator+fileName)); // writes the file to the upload dir
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
So to make the above class work. Download the commons-fileupload-1.2.1.jar and commons-io-1.4.jar. Now you are good to execute an File upload sample program using Apache commons.
-Murali*