Download a complete example tested under Tomcat 6 from here.
The YUI Uploader is a great upload component from Yahoo. This is a customizable component, with a great design that can accomplish from simple uploads to complex ones. Specifically, the YUI Uploader allows for (this features are taken from YUI Uploader site):
• Multiple file selection in a single "Open File" dialog.
• File extension filters to facilitate the user's selection.
• Progress tracking for file uploads.
• A range of available file metadata: filename, size, date created, date modified, and author.
• A set of events dispatched on various aspects of the file upload process: file selection, upload progress, upload completion, etc.
• Inclusion of additional data in the file upload POST request.
• Faster file upload on broadband connections due to the modified SEND buffer size.
• Same-page server response upon completion of the file upload.
In this post, you will see how to implement the YUI Uploader into a web application build in a Java context. For start, you must download YUI Uploader from
here. Depending on the web application context, to use the Uploader Control, include the following source files in your web page (in this example you stored the YUI Uploader into a folder named /yui under application root):
<script type="text/javascript" src="yui/build/yahoo-dom-event/yahoo-dom-event.js">
</script>
<script type="text/javascript" src="yui/build/element/element-min.js"></script>
<script type="text/javascript" src="yui/build/uploader/uploader-min.js"></script>
Next, you can place the code necessary for configure the YUI Uploader. First, you can see a few details about each representative chunk of code, and after that you will see the code :
First of all, you need to specify the path (relative to the page or absolute) of the uploader.swf file to the location of the HTML page in which a Uploader Control instance will appear and then render the uploader as a button.
// Instantiate the uploader and write it to its placeholder div.
YAHOO.widget.Uploader.SWFURL = "yui/resources/uploader.swf";
var uploader = new YAHOO.widget.Uploader( "uploaderUI",
"yui/resources/selectFileButton.png");
The Uploader has a number of methods that allows you to manage the upload process and dispatches various events for different aspects of the upload process. To add event listeners to various events called by the uploader you may do like this :
// Add event listeners to various events on the uploader.
// Methods on the uploader should only be called once the contentReady event has
// fired.
uploader.addListener('contentReady', handleContentReady);
uploader.addListener('fileSelect',onFileSelect)
uploader.addListener('uploadStart',onUploadStart);
uploader.addListener('uploadProgress',onUploadProgress);
uploader.addListener('uploadCancel',onUploadCancel);
uploader.addListener('uploadComplete',onUploadComplete);
uploader.addListener('uploadCompleteData',onUploadResponse);
uploader.addListener('uploadError', onUploadError);
Now, you need to define the event handlers. The first event that you need to create should be the contentReady witch will enable the logging output in the uploader (the log messages will be output both to the YUI Logger, and the Flash trace output), disallow multiple file selection and set file filters to filter user selection.
function handleContentReady () {
// Allows the uploader to send log messages to trace, as well as to YAHOO.log
uploader.setAllowLogging(true);
// Restrict selection to a single file (that's what it is by default,
// just demonstrating how).
uploader.setAllowMultipleFiles(false);
// New set of file filters.
var ff = new Array({description:"Images", extensions:"*.txt;*.jpg;*.png;*.gif"});
// Apply new set of file filters to the uploader.
uploader.setFileFilters(ff);
}
When the “Upload File” button is clicked, the upload function is called.
// Initiate the file upload. Since there's only one file,
// we can use either upload() or uploadAll() call. fileList
// needs to have been populated by the user.
function upload() {
if (fileID != null) {
uploader.upload(fileID, "http://localhost:8085/YUI_upload/oreilly_upload");
fileID = null;
}
}
When a file is selected, record the id of the selected file, disable the uploader UI, display the name of the file and reset the progress bar.
// Fired when the user selects files in the "Browse" dialog
// and clicks "Ok".
function onFileSelect(event) {
for (var item in event.fileList) {
if(YAHOO.lang.hasOwnProperty(event.fileList, item)) {
YAHOO.log(event.fileList[item].id);
fileID = event.fileList[item].id;
}
}
uploader.disable();
var filename = document.getElementById("fileName");
filename.innerHTML = event.fileList[fileID].name;
var progressbar = document.getElementById("progressBar");
progressbar.innerHTML = "";
}
The next function handles uploadProgress events, and draws a progress bar of correct size.
// Do something on each file's upload progress event.
function onUploadProgress(event) {
prog = Math.round(300*(event["bytesLoaded"]/event["bytesTotal"]));
progbar = "<div style=\"background-color: #f00; height: 5px; width: " +
prog + "px\"/>";
var progressbar = document.getElementById("progressBar");
progressbar.innerHTML = progbar;
}
Next, you need to handle the uploadComplete event, draws a full progress bar, and re-enables the uploader UI.
// Do something when each file's upload is complete.
function onUploadComplete(event) {
uploader.clearFileList();
uploader.enable();
progbar = "<div style=\"background-color: #CCCCCC; height: 5px; width: 300px\"/>";
var progressbar = document.getElementById("progressBar");
progressbar.innerHTML = progbar;
var filename = document.getElementById("fileName");
filename.innerHTML = "";
}
The code without comments is shown below:
...
<style type="text/css">
.uploadButton a, .clearButton a {
display:block;
width:100px;
height:40px;
text-decoration: none;
margin-left:5px;
}
.uploadButton a {
background: url("yui/resources/uploadFileButton.png") 0 0 no-repeat;
}
.clearButton a {
background: url("yui/resources/clearListButton.png") 0 0 no-repeat;
}
.uploadButton a:visited, .clearButton a:visited {
background-position: 0 0;
}
.uploadButton a:hover, .clearButton a:hover {
background-position: 0 -40px;
}
.uploadButton a:active, .clearButton a:active {
background-position: 0 -80px;
}
</style>
<div>
<div id="fileProgress" style="border: black 1px solid; width:300px; height:40px;
float:left">
<div id="fileName" style="text-align:center; margin:5px;
font-size:15px; width:290px; height:25px; overflow:hidden">
</div>
<div id="progressBar" style="width:300px;height:5px;background-color:#CCCCCC"></div>
</div>
<div id="uploaderUI" style="width:100px;height:40px; margin-left:5px;float:left">
</div>
<div class="uploadButton" style="float:left">
<a class="rolloverButton" href="#" onClick="upload(); return false;"></a>
</div>
<div class="clearButton" style="float:left"><a class="rolloverButton" href="#"
onClick="handleClearFiles(); return false;"></a></div>
</div>
<script type="text/javascript">
YAHOO.widget.Uploader.SWFURL = "yui/resources/uploader.swf";
var uploader = new YAHOO.widget.Uploader( "uploaderUI",
"yui/resources/selectFileButton.png" );
uploader.addListener('contentReady', handleContentReady);
uploader.addListener('fileSelect',onFileSelect)
uploader.addListener('uploadStart',onUploadStart);
uploader.addListener('uploadProgress',onUploadProgress);
uploader.addListener('uploadCancel',onUploadCancel);
uploader.addListener('uploadComplete',onUploadComplete);
uploader.addListener('uploadCompleteData',onUploadResponse);
uploader.addListener('uploadError', onUploadError);
// Variable for holding the selected file ID.
var fileID;
function handleClearFiles() {
uploader.clearFileList();
uploader.enable();
fileID = null;
var filename = document.getElementById("fileName");
filename.innerHTML = "";
var progressbar = document.getElementById("progressBar");
progressbar.innerHTML = "";
}
function handleContentReady () {
uploader.setAllowLogging(true);
uploader.setAllowMultipleFiles(false);
var ff = new Array({description:"Images", extensions:"*.txt;*.jpg;*.png;*.gif"});
uploader.setFileFilters(ff);
}
function upload() {
if (fileID != null) {
uploader.upload(fileID, "http://localhost:8080/YUI_upload/oreilly_upload");
fileID = null;
}
}
function onFileSelect(event) {
for (var item in event.fileList) {
if(YAHOO.lang.hasOwnProperty(event.fileList, item)) {
YAHOO.log(event.fileList[item].id);
fileID = event.fileList[item].id;
}
}
uploader.disable();
var filename = document.getElementById("fileName");
filename.innerHTML = event.fileList[fileID].name;
var progressbar = document.getElementById("progressBar");
progressbar.innerHTML = "";
}
// Do something on each file's upload start.
function onUploadStart(event) {
}
function onUploadProgress(event) {
prog = Math.round(300*(event["bytesLoaded"]/event["bytesTotal"]));
progbar = "<div style=\"background-color: #f00; height: 5px; width: " +
prog + "px\"/>";
var progressbar = document.getElementById("progressBar");
progressbar.innerHTML = progbar;
}
function onUploadComplete(event) {
uploader.clearFileList();
uploader.enable();
progbar = "<div style=\"background-color: #CCCCCC; height: 5px; width: 300px\"/>";
var progressbar = document.getElementById("progressBar");
progressbar.innerHTML = progbar;
var filename = document.getElementById("fileName");
filename.innerHTML = "";
}
// Do something if a file upload throws an error.
// (When uploadAll() is used, the Uploader will
// attempt to continue uploading.
function onUploadError(event) {
}
// Do something if an upload is cancelled.
function onUploadCancel(event) {
}
// Do something when data is received back from the server.
function onUploadResponse(event) {
alert("Server response successfully received!");
}
</script>
...
For this application you can use the COS described in this post
How to upload in Java (Upload using the COS library) . The result of this application is shown below in figure below:

Download a complete example tested under Tomcat 6 from here.