Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Ajax Ajax File Upload Example

Related Tutorials


 
 

Share on Google+Share on Google+

Ajax File Upload Example

Advertisement
This application illustrates how to upload a file using servlet through the Ajax technology.

Ajax File Upload Example

     

This application illustrates how to upload a file using servlet through the Ajax technology.

In this example you simply create a file Upload application using ajax just follows by these points:

  • Create a simple HTML form for file upload
  • Set the target to an iFrame which is on the actual page but not visible
  • Call a JavaScript function on form submit to call the servlet
  • And the servlet finishes the all upload process.

To understand the way this works I think it is easiest to break it down into parts:

  1. A file upload extention that counts bytes as they are uploaded
  2. An interface that monitors the progress of something running on the server
  3. AJAX to pull the monitoring into the current screen

 

The Entire Application is as follows:

 

 

Source Code of fileUpload.html 

<html>
<head>
<title>Ajax File Upload</title>
<script language="javascript">
var req;

function ajaxFunction(){
  var url = "example/FileUploadServlet";

  if (window.XMLHttpRequest){ 
  req = new XMLHttpRequest();
  req.onreadystatechange = processStateChange;

  try{
  req.open("GET", url, true);
  catch (e) {
  alert(e);
  }
  req.send(null);
  else if (window.ActiveXObject) { 
  req = new ActiveXObject("Microsoft.XMLHTTP");
  
  if (req) {
  req.onreadystatechange = processStateChange;
  req.open("GET", url, true);
  req.send();
  }
  }
}

function processStateChange(){
  if (req.readyState == 4){
  if (req.status == 200){
  var xml = req.responseXML;
  var isNotFinished = xml.getElementsByTagName
   (
"finished")[0];
  var myBytesRead = xml.getElementsByTagName
   (
"bytes_read")[0];
  var myContentLength = xml.getElementsByTagName
   (
"content_length")[0];
  var myPercent = xml.getElementsByTagName
  (
"percent_complete")[0];
  if ((isNotFinished == null&& (myPercent == null)){
  document.getElementById("initializing").style.
  visibility = 
"visible";
  window.setTimeout("ajaxFunction();"100);
  else {
  document.getElementById("initializing").style.
  visibility = 
"hidden";
  document.getElementById("progressBarTable").style.
  visibility = 
"visible";
  document.getElementById("percentCompleteTable").style.
   visibility = 
"visible";
  document.getElementById("bytesRead").style.
   visibility = 
"visible";

  myBytesRead = myBytesRead.firstChild.data;
  myContentLength = myContentLength.firstChild.data;

  if (myPercent != null) {
  myPercent = myPercent.firstChild.data;
  
  document.getElementById("progressBar").style.width 
  = myPercent + 
"%";
  document.getElementById("bytesRead").innerHTML 
   = myBytesRead + 
" of " 
  myContentLength + " bytes read";
  document.getElementById("percentComplete").innerHTML 
  = myPercent + 
"100%";
  window.setTimeout("ajaxFunction();"100);
  else {
  document.getElementById("bytesRead").style.visibility 
   = 
"hidden";
  document.getElementById("progressBar").style.width 
   = 
"100%";
  document.getElementById("percentComplete").innerHTML 
  = 
"File Uploading Done!";
  document.getElementById("txtFile").value="";
  }
  }
  else {
  alert(req.statusText);
  }
  }
}
</script>
</head>
<body>
  <iframe id="uploadFrameID" name="uploadFrame" height="0" width="0" 
 
frameborder="0" scrolling="yes"></iframe>  
  <form id="myForm" enctype="multipart/form-data" method="post" 
  
target="uploadFrame" 
  action="example/FileUploadServlet" onsubmit="ajaxFunction()">
  <input type="file" name="txtFile" id="txtFile" /><br />
  <input type="submit" id="submitID" name="submit" value=
  "Upload" 
/>
  </form>
  
  <div id="initializing" style="visibility: hidden; position: 
   absolute; top: 100px;"
>
  <table width="100%" style="border: 1px; background-color: black;">
  <tr>
  <td>
  <table width="100%" style="border: 1px; background-color:
    black; color: white;"
>
  <tr>
  <td align="center">
  <b>Initializing Upload...</b>
  </td>
  </tr>
  </table>
  </td>
  </tr>
  </table>
  </div>
  
  <div id="progressBarTable" style="visibility: hidden; position: 
  absolute; top: 100px;"
>
  <table width="100%" style="border: 1px; color: white;">
  <tr>
  <td>
  <table id="progressBar" width="100%" >
  <tr>
  <td>&nbsp;</td>
  </tr>
  </table>
  </td>
  </tr>
  </table>
  <table width="100%" style="background-color: white; color: black;">
  <tr>
  <td align="center" nowrap="nowrap">
  <span id="bytesRead" style="font-weight: bold;">&nbsp;</span>
  </td>
  </tr>
  </table>  
  </div>

  <div id="percentCompleteTable" align="center"
  style="visibility: hidden; position: absolute; top: 100px;">
  <table width="100%" style="border: 1px;">
  <tr>
  <td>
  <table width="100%" style="border: 1px;">
  <tr>
  <td align="center"  width="100%">
 <span id="percentComplete" style="color: blue; 
   font-weight: bold; width:100%"
>&nbsp;</span>
  </td>
  </tr>
  </table>
  </td>
  </tr>
  </table>
 </div>
</body>
</html>

 

Source Code of FileUploadServlet.java 

package fileupload;

import javax.servlet.Servlet;
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 long serialVersionUID = 2740693677625051632L;

  public FileUploadServlet(){
  super();
  }

  protected void doGet(HttpServletRequest request,
   HttpServletResponse response

   throws 
ServletException, IOException {
  PrintWriter out = response.getWriter();
  HttpSession session = request.getSession();
  FileUploadListener listener = null
  StringBuffer buffy = new StringBuffer();
  long bytesRead = 0,  contentLength = 0

  if (session == null){
  return;
  else if (session != null){
  listener = (FileUploadListener)session.getAttribute("LISTENER");
  
  if (listener == null){
  return;
  else {
  bytesRead = listener.getBytesRead();
  contentLength = listener.getContentLength();
  }
  }
  
  response.setContentType("text/xml");
  
  buffy.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
  buffy.append("<response>\n");
  buffy.append("\t<bytes_read>" + bytesRead + "</bytes_read>\n");
  buffy.append("\t<content_length>" 
 
+ contentLength + "</content_length>\n");

  if (bytesRead == contentLength) {
  buffy.append("\t<finished />\n");
  session.setAttribute("LISTENER"null);
  else {
  long percentComplete = ((100 * bytesRead/ contentLength);  
  buffy.append("\t<percent_complete>" 
   + percentComplete + 
"</percent_complete>\n");
  }  
  buffy.append("</response>\n");
  out.println(buffy.toString());
  out.flush();
  out.close();
  }
  
  protected void doPost(HttpServletRequest request, 
  HttpServletResponse response

   throws 
ServletException, IOException {
  FileItemFactory factory = new DiskFileItemFactory();
  ServletFileUpload upload = new ServletFileUpload(factory);
  FileUploadListener listener = new FileUploadListener();
  HttpSession session = request.getSession();
  session.setAttribute("LISTENER", listener);
  upload.setProgressListener(listener);
  List uploadedItems = null;
  FileItem fileItem = null;
  String filePath = "c:\\temp";

  try {
  uploadedItems = upload.parseRequest(request);
  Iterator i = uploadedItems.iterator();
  
  while (i.hasNext())  {
  fileItem = (FileItemi.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(filePath, myFileName);
  fileItem.write(uploadedFile);
  }
  }
  }
  catch (FileUploadException e) {
  e.printStackTrace();
  catch (Exception e) {
  e.printStackTrace();
  
  
}

 

Source Code of FileUploadListener.java 

package fileupload;

import org.apache.commons.fileupload.ProgressListener;

public class FileUploadListener implements ProgressListener{
  private volatile long bytesRead = 0L
  contentLength = 
0L, item = 0L;

  public FileUploadListener() {
  super();
  }

  public void update(long aBytesRead, 
   long 
aContentLength, int anItem) {
  bytesRead = aBytesRead;
  contentLength = aContentLength;
  item = anItem;
  }

  public long getBytesRead() {
  return bytesRead;
  }

  public long getContentLength() {
  return contentLength;
  }

  public long getItem() {
  return item;
  }
}

 

Download Complete Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 25, 2009

Related Tutorials

Discuss: Ajax File Upload Example   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:4
Rohin
April 9, 2011
Problem Regarding File Upload

Please help me , there is an issue regarding file upload i.e. when i click on BROWSE Button in file upload control its browsing path is different when i click again on BROWSE Button,, in WINDOW-7 in asp.net using c# ... please help me that i want same path when user last time click path......its works right in window-xp Please help me as soon as possible,,,i'm waiting for ur response...
bekir
April 11, 2011
not working

Hello, I am using tomcat 7 and jdk6. I get the following error: java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletRequest at org.apache.commons.fileupload.servlet.ServletRequestContext.getContentType(ServletRequestContext.java:73) at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:905) at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331) at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:351) at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126) at uploadlibs.FileUploadServlet.doPost(FileUploadServlet.java:88) at javax.servlet.http.HttpServlet.service(HttpServlet.java:641) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:662)
rajesh
January 14, 2012
always showing alert message "Not Found"

when, i'm running the above program/code, it's showing "Not Found".
prasantaghoshal
April 25, 2012
php

Sir , I have a request to ur honour that my first question is :====== I want to display calender of current month created by php and when i would click or press on date that would be displayed as a text inside a textbox my second question is :====== suppose I want to display calender of previous month created by php and when i would click or press on date only those dates will be marked as red circle and how many dates have been clicked would be calculated and for those days salary will be deducted from total salary Sir I want these two problems to be solved ? if U help me I would highly obliged to u ...
DMCA.com