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


Ajax File Upload




target="uploadFrame"
action="example/FileUploadServlet" onsubmit="ajaxFunction()">


"Upload" />






style="visibility: hidden; position: absolute; top: 100px;">










 








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("\n");
buffy.append("\n");
buffy.append("\t" + bytesRead + "\n");
buffy.append("\t" + contentLength + "\n");

if (bytesRead == contentLength) {
buffy.append("\t\n");
session.setAttribute("LISTENER", null);
} else {
long percentComplete = ((100 * bytesRead) / contentLength);
buffy.append("\t" + percentComplete + "\n");
}
buffy.append("
\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 = (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(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

0 comments:

Post a Comment