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:
- A file upload extention that counts bytes as they are uploaded
- An interface that monitors the progress of something running on the server
- 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> </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;"> </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%"> </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 = (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