Introduction
In this tutorial you
will learn about Asynchronous File Upload using Ajax, jQuery
Progress Bar and Java
The image below shows
a screenshot of the file upload that we are going to learn in this tutorial.
Let us see what all is needed to develop this application. We
shall create a web application which has the following files.
·
FileUpload.html (The
html/jsp file where the file upload happens)
·
jQuery related script
files(We are going to discuss about this in detail later)
·
FileUploadListener.java(The
listener file which listens to the file upload)
·
FileUploadListener.java
(The servlet file which takes care of the upload process)
·
web.xml
The image below shows
the screenshot of the file Structure. We have used netBeans IDE to develop the
web Application.
File Structure
Let us try to understand the webstructure.We have a web folder
which has FileUpload.html.The source packages has a
java package “fileupload” which has two java files FileUploadListener.java and FileUploadServlet.java
There is another
folder called “scripts” which has jquery.js which is used for the
core javascript and Ajax features of jQuery library.
Apart from this we
also have ui.core.js and ui.progressbar.js.
These files are necessary for constructing a progress bar using jQuery.You can
download the latest version of jQuery from Download jQuery
The jquery progress
bar can be downloaded from Download jQuery
UI
Now let us add in code
into FileUpload.html
We shall be adding
script , style and html body sections to the html files. Lets deal with each
one of these sections one after the other.
Please find below the
code for the html body section.
Html Body Code
1
|
<body>
|
|
2
|
<center>
|
3
|
<h2 class="backgroundClass">Sample
File Upload</h2>
|
|
4
|
<form id="myForm" enctype="multipart/form-data" method="post" target="uploadFrame"
|
5
|
action="example/FileUploadServlet" onsubmit="ajaxFunction()">
|
|
6
|
<table border="1">
|
7
|
<tr><td>
<h4>File to be uploaded </h4></td><td>
<input type="file" name="txtFile" id="txtFile" /></td></tr>
|
|
8
|
<tr><td align="center" colspan="2">
<input type="submit" id="submitID" name="submit" value="Upload" /></td></tr>
|
|
9
|
</table>
|
||
10
|
</form>
|
||
11
|
<div id="progressbarWrapper" style="height:20px;width:100px;
">
|
|
12
|
<div id="progressbar" style="height:100%;"></div>
|
13
|
</div>
|
|
14
|
<br/>
|
15
|
<div id="status" style="display:none">
|
|
16
|
<table width="100%" class="backgroundClass">
|
17
|
<tr>
|
|
18
|
<td align="center" nowrap="nowrap">
|
19
|
<div id="percentDone" style="font-weight:
bold;"> </span>
|
|
20
|
</td>
|
21
|
</tr>
|
22
|
</table>
|
23
|
<table width="100%" class="backgroundClass">
|
|
24
|
<tr>
|
25
|
<td align="center" nowrap="nowrap">
|
|
26
|
<div id="bytesRead" style="font-weight:
bold;"> </span>
|
27
|
</td>
|
28
|
</tr>
|
29
|
</table>
|
|
30
|
<table width="100%" class="backgroundClass">
|
31
|
<tr>
|
|
32
|
<td align="center" nowrap="nowrap">
|
33
|
<div id="totalNoOfBytes" style="font-weight:
bold;"> </span>
|
|
34
|
</td>
|
35
|
</tr>
|
|
36
|
</table>
|
37
|
</div>
|
|
38
|
</center>
|
39
|
</body>
|
Script Code
Add the following code
to the script section.
The script code pasted
below will import the various script files necessary for jQuery core functions,
progress bar and Ajax.
After importing, we
need to do the following tasks:
·
Add the progressbar to
the page(The progress bar will be hidden on the load of the page and will be
shown only when the file upload begins.)
·
Make an Ajax request
to the java Servlet(Servlet code will be discussed later).The Java Servlet will
take care of the file upload on the server.
·
The ajaxFunction() will
take care of sending the xmlHttpRequest.
·
funcReadyStateChange() will be invoked soon after getting the
output.It takes care of the collecting the servlet output which is in the form
of XML.funcReadyStateChange()will also take care of:
o
Parsing the response
XML.
o
Updating the progress
bar value through updateProgressbar() function
o
Update the page with
the response.
·
The output xml will
have details about the total number of bytes present in the file and the number
of bytes uploaded.
·
Please note that the funcReadyState
will make repetitive calls to ajaxFunction() and updateProgressBar() until the
file is completely uploaded.Every request that is sent will get the recent most
values of the “number of bytes that are uploaded” from the server.
1
|
<script src="scripts/jquery.js"></script>
|
|
2
|
<script
src="scripts/ui.core.js"></script>
|
3
|
<script
src="scripts/ui.progressbar.js"></script>
|
|
4
|
<script
src="scripts/ui.resizable.js"></script>
|
5
|
<script>
|
|
6
|
var
progressBarValue=0;
|
7
|
$(document).ready(function()
{
|
|
8
|
$( "#progressbar" ).progressbar({
value:0 });
|
9
|
document.getElementById("progressbarWrapper").style.display
= "none";
|
||
10
|
});
|
||
11
|
function
updateProgressBar(progressBarValue)
|
|
12
|
{
|
13
|
$("#progressbar").progressbar("option","value",progressBarValue);
|
|
14
|
}
|
15
|
var req;
|
|
16
|
|
17
|
function
ajaxFunction(){
|
|
18
|
var
url = "example/FileUploadServlet";
|
19
|
|
|
20
|
if (window.XMLHttpRequest){
|
21
|
req
= new XMLHttpRequest();
|
|
22
|
try{
|
23
|
req.onreadystatechange
= funcReadyStateChange;
|
|
24
|
req.open("GET",
url, true);
|
25
|
} catch (e) {
|
|
26
|
alert(e);
|
27
|
}
|
|
28
|
req.send(null);
|
29
|
}
|
|
30
|
|
31
|
else if (window.ActiveXObject)
{
|
|
32
|
req
= new ActiveXObject("Microsoft.XMLHTTP");
|
33
|
if (req) {
|
|
34
|
req.onreadystatechange
= funcReadyStateChange;
|
35
|
req.open("GET",
url, true);
|
|
36
|
req.send();
|
37
|
}
|
|
38
|
}
|
39
|
}
|
|
40
|
|
41
|
function
funcReadyStateChange(){
|
|
42
|
if (req.readyState
== 4){
|
43
|
if (req.status
== 200){
|
|
44
|
var
xml = req.responseXML;
|
45
|
var
responseNode=xml.getElementsByTagName("response")[0];
|
46
|
var
noOfBytesRead =responseNode.getElementsByTagName("bytes_read")[0].
|
47
|
childNodes[0].nodeValue;
|
|
48
|
var
totalNoOfBytes =
responseNode.getElementsByTagName("content_length")[0].
|
49
|
childNodes[0].nodeValue;
|
||
50
|
progressBarValue=noOfBytesRead/totalNoOfBytes*100;
|
||
51
|
document.getElementById("status").style.display="block";
|
|
52
|
document.getElementById("percentDone").innerHTML="Percentage
Completed: "
|
|
53
|
+Math.floor(progressBarValue)+"%";
|
|
54
|
document.getElementById("bytesRead").innerHTML= "Number
Of Bytes Read: "+
|
55
|
noOfBytesRead;
|
||
56
|
document.getElementById("totalNoOfBytes").innerHTML= "Total
Number Of Bytes: "+
|
||
57
|
totalNoOfBytes;
|
||
58
|
document.getElementById("progressbarWrapper").style.display
= "block";
|
||
59
|
|
|
60
|
if (progressBarValue<100){
|
61
|
window.setTimeout("ajaxFunction();", 100);
|
||
62
|
window.setTimeout("updateProgressBar(progressBarValue);", 100);
|
||
63
|
|
64
|
} else {
|
65
|
alert("Done");
|
|
66
|
window.setTimeout("updateProgressBar(100);", 100);
|
67
|
document.getElementById("progressbarWrapper").style.display
= "none";
|
|
68
|
document.getElementById("status").style.display="none";
|
|
69
|
}
|
|
70
|
} else {
|
71
|
alert(req.statusText);
|
|
72
|
}
|
73
|
}
|
|
74
|
}
|
75
|
</script>
|
Style Code
Now add the following
code to the style section.
1
|
|||
2
|
rel="stylesheet" type="text/css"/>
|
||
3
|
<link href="style/ui.all.css" rel="stylesheet" type="text/css"/>
|
|
4
|
<link href="style/ui.core.css" rel="stylesheet" type="text/css"/>
|
5
|
<link href="style/ui.progressbar.css" rel="stylesheet" type="text/css"/>
|
|
6
|
<style type="text/css">
|
7
|
.ui-progressbar-value
{ background-image: url(images/progressBarImage.jpg); }
|
|
8
|
.backgroundClass
|
9
|
{
|
||
10
|
background-image:
url(images/background.jpg);
|
||
11
|
color:white;
|
|
12
|
}
|
13
|
</style>
|
Listener Code
This listener will
listen to the event of file upload and has a method called fileUpdate() which
will be automatically invoked as and when there is an update on fileUpload.
1
|
package fileupload;
|
|
2
|
import org.apache.commons.fileupload.ProgressListener;
|
3
|
public class FileUploadListener implements ProgressListener{
|
|
4
|
private volatile long bytesRead = 0L,
contentLength = 0L, item = 0L;
|
5
|
public FileUploadListener()
{
|
|
6
|
super();
|
7
|
}
|
|
8
|
|
9
|
public void update(long aBytesRead, long aContentLength, int anItem) {
|
||
10
|
bytesRead
= aBytesRead;
|
||
11
|
contentLength
= aContentLength;
|
|
12
|
item
= anItem;
|
13
|
}
|
|
14
|
|
15
|
public long getBytesRead() {
|
|
16
|
return bytesRead;
|
17
|
}
|
|
18
|
|
19
|
public long getContentLength() {
|
|
20
|
return contentLength;
|
21
|
}
|
|
22
|
|
23
|
public long getItem() {
|
|
24
|
return item;
|
25
|
}
|
|
26
|
}
|
Servlet Code
The servlet will get
the information about the number of bytes read through the listener and will
construct a response xml with tags “bytes-read” and “content-length” etc.
1
|
package fileupload;
|
|
2
|
|
3
|
import javax.servlet.Servlet;
|
|
4
|
import javax.servlet.http.HttpServlet;
|
5
|
import java.io.*;
|
|
6
|
import java.util.*;
|
7
|
import javax.servlet.http.*;
|
|
8
|
import org.apache.commons.fileupload.*;
|
9
|
import javax.servlet.ServletException;
|
||
10
|
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
|
||
11
|
import org.apache.commons.fileupload.servlet.ServletFileUpload;
|
|
12
|
|
13
|
public class FileUploadServlet extends HttpServlet implements Servlet {
|
|
14
|
|
15
|
private static final long serialVersionUID =
2740693677625051632L;
|
|
16
|
|
17
|
public FileUploadServlet()
{
|
|
18
|
super();
|
19
|
}
|
|
20
|
|
21
|
protected void doGet(HttpServletRequest
request, HttpServletResponse response) throws ServletException,
IOException {
|
|
22
|
PrintWriter
out = response.getWriter();
|
23
|
HttpSession
session = request.getSession();
|
|
24
|
FileUploadListener
listener = null;
|
25
|
StringBuffer
buffy = new StringBuffer();
|
|
26
|
long bytesRead = 0,
contentLength = 0;
|
27
|
|
|
28
|
if (session
== null) {
|
29
|
return;
|
|
30
|
} else if (session
!= null) {
|
31
|
listener
= (FileUploadListener) session.getAttribute("LISTENER");
|
|
32
|
|
33
|
if (listener
== null) {
|
|
34
|
return;
|
35
|
} else {
|
|
36
|
bytesRead
= listener.getBytesRead();
|
37
|
contentLength
= listener.getContentLength();
|
|
38
|
}
|
39
|
}
|
|
40
|
|
41
|
response.setContentType("text/xml");
|
|
42
|
|
43
|
buffy.append("<?xml
version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
|
|
44
|
buffy.append("<response>\n");
|
45
|
buffy.append("\t<bytes_read>" + bytesRead
+ "</bytes_read>\n");
|
|
46
|
buffy.append("\t<content_length>" + contentLength
+ "</content_length>\n");
|
47
|
|
|
48
|
if (bytesRead ==
contentLength) {
|
49
|
buffy.append("\t<finished
/>\n");
|
|
50
|
session.setAttribute("LISTENER", null);
|
51
|
} else {
|
|
52
|
long percentComplete =
((100 * bytesRead) / contentLength);
|
53
|
buffy.append("\t<percent_complete>" + percentComplete
+ "</percent_complete>\n");
|
|
54
|
}
|
55
|
buffy.append("</response>\n");
|
56
|
out.println(buffy.toString());
|
57
|
out.flush();
|
58
|
out.close();
|
59
|
}
|
|
60
|
|
61
|
protected void doPost(HttpServletRequest
request, HttpServletResponse response) throws ServletException,
IOException {
|
|
62
|
FileItemFactory
factory = new DiskFileItemFactory();
|
63
|
ServletFileUpload
upload = new ServletFileUpload(factory);
|
|
64
|
FileUploadListener
listener = new FileUploadListener();
|
65
|
HttpSession
session = request.getSession();
|
66
|
session.setAttribute("LISTENER",
listener);
|
67
|
upload.setProgressListener(listener);
|
|
68
|
List
uploadedItems = null;
|
69
|
FileItem
fileItem = null;
|
|
70
|
String
filePath = "c:\\temp";
|
71
|
|
|
72
|
try {
|
73
|
uploadedItems
= upload.parseRequest(request);
|
|
74
|
Iterator
i = uploadedItems.iterator();
|
75
|
|
|
76
|
while (i.hasNext()) {
|
77
|
fileItem
= (FileItem) i.next();
|
|
78
|
if (fileItem.isFormField()
== false) {
|
79
|
if (fileItem.getSize()
> 0) {
|
|
80
|
File
uploadedFile = null;
|
81
|
String
myFullFileName = fileItem.getName(), myFileName = "",
slashType = (myFullFileName.lastIndexOf("\\") > 0)
? "\\" : "/";
|
82
|
int startIndex =
myFullFileName.lastIndexOf(slashType);
|
83
|
myFileName
= myFullFileName.substring(startIndex + 1, myFullFileName.length());
|
|
84
|
uploadedFile
= new File(filePath, myFileName);
|
85
|
fileItem.write(uploadedFile);
|
|
86
|
}
|
87
|
}
|
|
88
|
}
|
89
|
} catch (FileUploadException
e) {
|
|
90
|
e.printStackTrace();
|
91
|
} catch (Exception e) {
|
|
92
|
e.printStackTrace();
|
93
|
}
|
|
94
|
}
|
95
|
}
|
web.xml
We need to declare the
servlet and also the listener in web.xml.
1
|
<servlet>
|
|
2
|
<servlet-name>UploadServlet
</servlet-name>
|
3
|
<servlet-class>fileupload.FileUploadServlet</servlet-class>
|
|
4
|
</servlet>
|
5
|
<servlet-mapping>
|
|
6
|
<servlet-name>UploadServlet</servlet-name>
|
7
|
<url-pattern>/example/FileUploadServlet</url-pattern>
|
|
8
|
</servlet-mapping>
|
9
|
<listener>
|
||
10
|
<listener-class>fileupload.FileUploadListener</listener-class>
|
||
11
|
</listener>- See more at:
http://www.javabeat.net/asynchronous-file-upload-using-ajax-jquery-progress-bar-and-java/#sthash.4mmIeZdp.dpuf
- See more at: http://www.javabeat.net/asynchronous-file-upload-using-ajax-jquery-progress-bar-and-java/#sthash.4mmIeZdp.dpuf
- See more at:
http://www.javabeat.net/asynchronous-file-upload-using-ajax-jquery-progress-bar-and-java/#sthash.4mmIeZdp.dpuf
|
No comments:
Post a Comment