10/18/2011

Ajax Styled Servlet File upload

This is very simple application to upload a file using java servlet like AJAX.
1. Create a web project

2. Download two jar files commons-fileupload-1.2.2.jar  commons-io-2.0.1.jar and put it into 
    /WEB-INF/lib/ under your project.

3. create any html file under your webApp write these following tags
     <form action="ajaxupload" enctype="multipart/form-data" method="post" target="iframe">
         <input type="file" name="fileTxtUpload">
         <input type="submit">
    </form>

4. Now you need to write a tagline for iFrame anywhere on the page but outside of <form> </form>. 
   <iframe name="iframe" id="iframeid" width="0" height="0" style="visibility: hidden">   </iframe>

5. Now create a folder "files" under your webApp. All the uploaded files would be save here

6. Please copy the servlet class and map approprite in web.xml. 


import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;


import java.io.*;
import java.util.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import javax.servlet.ServletException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class FileUploadServlet extends HttpServlet implements Servlet {
private static final String DESTINATION_DIR_PATH = "/files";   /* directory : where-ever you want to save in disk. as i am saving into the context */
    protected File destinationDir = null;
protected PrintWriter out = null;
   
public void init(ServletConfig config) throws ServletException {
super.init(config);
String destination_realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
System.out.println(destination_realPath);
destinationDir = new File(destination_realPath);
if(!destinationDir.isDirectory()) {
throw new ServletException(DESTINATION_DIR_PATH+" is not a directory");
}
}

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List uploadedItems = null;
FileItem fileItem = null;

        out = response.getWriter();
try {
uploadedItems = upload.parseRequest(request);
Iterator i = uploadedItems.iterator();
System.out.println(uploadedItems.isEmpty() + " : " + i.hasNext());
while (i.hasNext()) {
fileItem = (FileItem) i.next();
 if(fileItem.isFormField() == false) {
if(fileItem.getSize() > 0) {
File uploadedFile = null; 
String myFullFileName = fileItem.getName(), myFileName = "", slashType = (myFullFileName.lastIndexOf("\\") > 0) ? "\\" : "/";
int startIndex = myFullFileName.lastIndexOf(slashType);
myFileName = myFullFileName.substring(startIndex + 1, myFullFileName.length());
uploadedFile = new File(destinationDir, myFileName);
fileItem.write(uploadedFile);
out.write(destinationDir + "\\" + myFileName );
   out.flush();
   out.close();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doPost(request, response);
    }       
}

 7. if  you want to get alert when the file is successfully uploaded, please write the following JS function inside header (<head> .. . .  </head>) section.


window.onload = function() {
 var iframe = document.getElementById("iframeid"),
     textBox = document.getElementById("textBox");
   iframe.onload = function(){
     /* parsing the data i.e. send from server side */
       var filePath = (iframe.contentWindow.document).getElementsByTagName('pre')[0].childNodes[0].nodeValue;
          alert("file is saved at your disk " + "\n"  + filePath);
 
       }
}