Example: Simple Uploader with Progress Tracking

This example demonstrates how to use the YUI 3 Uploader to send a single image or video (filtered by file extension) to the server and to monitor the upload progress. The example also shows how to use a custom image skin for the "Browse" button used by the Uploader.

Please note: This example will not work when run from a local filesystem because Flash only allows ExternalInterface communication with pages loaded from the network. If you’d like to run this example locally, set up a local web server and launch it from there.

Also note: The uploader is not supported on iOS devices (iPhone and iPad), because Flash player is not available on that system. This example will not function on such devices.

File selected:
Percent uploaded:

Set up the Uploader UI

The Uploader requires that the "Browse" button be implemented as an instance of the Flash Player; all other controls can be regular DOM elements. For this example, set up a container for the Flash Player and give it the id selectButton and set up a container for the "Upload" button (uploadButton). In addition, set up containers to display the name of the selected file (filename) and the progress of the upload (percent).

<div id="selectButton" style="width:100px;height:40px"></div> 
<div class="uploadButton"><a href="#" id="uploadButtonLink"></a></div>

<div id="filename">
File selected:
</div>
<div id="percent">
Percent uploaded:
</div>

In the head section of the example, define custom styles for the uploadButton to give it an image skin that has multiple button states:

<style type="text/css">
	.uploadButton a {
		display:block;
		width:100px;
		height:40px;
		text-decoration: none;
	}

	.uploadButton a {
		background: url("assets/uploadFileButton.png") 0 0 no-repeat;
	}

    .uploadButton a:visited {
		background-position: 0 0;
	}

    .uploadButton a:hover {	
		background-position: 0 -40px;
	}

    .uploadButton a:active {
		background-position: 0 -80px;
	}
</style>

Create a YUI Instance

Now that the UI containers and controls are in place, create a YUI instance, using the uploader module, for this example:

YUI().use("uploader", function(Y) {
	// Y is the YUI instance.
	// The rest of the code in this tutorial is encapsulated 
	// in this anonymous function.
} );

Working around the IE Caching Bug

Due to a bug in IE6 through IE8, when a SWF is loaded from local cache (after a page has been reloaded, for example), it's unable to properly communicate with the JavaScript VM. For that reason, specifically for IE, we can prevent loading the SWF from cache by appending a random get variable to the SWF URL:

var swfURL = Y.Env.cdn + "uploader/assets/uploader.swf";

if (Y.UA.ie >= 6) {
    swfURL += "?t=" + Y.guid();
}

Instantiate the Uploader

Next, create an instance of an Uploader and configure it. The Uploader only requires the reference to the container in which the "Browse" button should be placed, but in this example an image skin for the button is being used; as result, we need to provide the buttonSkin property with a reference to the image sprite, as well as the transparent Boolean value (this property specifies whether the transparent areas of the image sprite are rendered as such; if no buttonSkin is specified, the entire uploader would render as transparent). Also note that we are including a custom SWF URL, defined in the workaround above (by default, the SWF URL would be as shown above, but unmodified):

var uploader = new Y.Uploader({boundingBox:"#selectButton", 
                               buttonSkin:"assets/selectFileButton.png",
                               transparent: false,
                               swfURL: swfURL
                              });

Listen for Uploader Events

Next, add event handlers to various uploader events and the click handler for the "Upload" button. The uploaderReady event is particularly important because the uploader may not be ready to accept method calls until this event has fired. Therefore, any method calls and property settings for the uploader should be made within the handler for that event:

uploader.on("uploaderReady", setupUploader);
uploader.on("fileselect", fileSelect);
uploader.on("uploadprogress", updateProgress);
uploader.on("uploadcomplete", uploadComplete);

Y.one("#uploadButtonLink").on("click", uploadFile);

Set Up the Uploader

Once the uploader is ready, and the uploaderReady event is fired, set properties to further configure the Uploader. In particular, set the multiFiles property to restrict user to selecting only a single file, the log property to provide debug information (output only if the computer is running the debug version of the Flash player), and the fileFilters property to filter files in the user's "Browse" dialog:

function setupUploader (event) {
	uploader.set("multiFiles", false);
	uploader.set("log", true);
	
	var fileFilters = new Array({description:"Images", extensions:"*.jpg;*.png;*.gif"},
	                   {description:"Videos", extensions:"*.avi;*.mov;*.mpg"}); 
	
    uploader.set("fileFilters", fileFilters);
}

Handler for the fileselect Event

In the handler for the fileselect, extract the file list from the event payload and display the name of the file. In this particular case, the list should only contain one file name, since the user was restricted to selecting a single file:

function fileSelect (event) {
	var fileData = event.fileList;	

	for (var key in fileData) {
		var output = "File selected: " + fileData[key].name;
		Y.one("#filename").setHTML(output);
	}
}

Handler for Other Events

In the uploadprogress handler, update the content of the percent container based on the values provided in the event payload. In the uploadcomplete handler, place the final message into the percent container. Finally, in the click handler, initiate the upload to a specific URL:

function updateProgress (event) {
	Y.one("#percent").setHTML("Percent uploaded: " + Math.round((100 * event.bytesLoaded / event.bytesTotal)) + "%");
}

function uploadComplete (event) {
	Y.one("#percent").setHTML("Upload complete!");
}

function uploadFile (event) {
	uploader.uploadAll("http://www.yswfblog.com/upload/upload_simple.php");
}

Full Source Code For this Example

<style type="text/css">

.progressbars {
	width:300px;
}

.yui3-progressbar {
	margin-bottom:3px;
	border: 2px solid #c4c4c4;
	border-radius:5px;
	-moz-border-radius: 5px;
	-webkit-border-radius:5px;
}
.yui3-progressbar .yui3-progressbar-content {
	background-color:#fff;
	position:relative;
/*	width: 200px; */
}
.yui3-progressbar .yui3-progressbar-label {
	position: absolute;
	top:1px;
	left:3px;
	font-size:11px;
	font-family:Arial,Helvetica,sans-serif;
}
.yui3-progressbar .yui3-progressbar-slider {
	background-color:#e0bb30;
	height: 15px;
	line-height: 29px;
	width: 0;
}

#selectFilesLink #selectLink,
#uploadFilesLink #uploadLink {
    color: #00c;
    text-decoration: underline;
}
</style>

<div id="uploaderContainer"> 
	<div id="uploaderOverlay" style="position:absolute; z-index:2"></div> 
	<div id="selectFilesLink" style="z-index:1"><a id="selectLink" href="#">Select Files</a></div> 
</div> 
<div id="uploadFilesLink"><a id="uploadLink" href="#">Upload Files</a></div>

<div id="files">
  <table id="filenames" style="border-width:1px; border-style:solid; padding:5px;">
    <thead>
	   <tr><th>Filename</th><th>File size</th><th>Percent uploaded</th></tr>
	</thead>
	<tbody>
	</tbody>
  </table>	
</div>

<script>

YUI({filter:"raw", gallery: 'gallery-2011.02.09-21-32'}).use("uploader-deprecated", 'gallery-progress-bar', function(Y) {
	
var uploader,
    selectedFiles = {};

function init () {
var overlayRegion = Y.one("#selectLink").get('region');
Y.one("#uploaderOverlay").set("offsetWidth", overlayRegion.width);
Y.one("#uploaderOverlay").set("offsetHeight", overlayRegion.height);


 
var swfURL = ../../build/uploader-deprecated/assets/uploader.swf; 


if (Y.UA.ie >= 6) {
	swfURL += "?t=" + Y.guid();
}

uploader = new Y.Uploader({boundingBox:"#uploaderOverlay", 
                           swfURL: swfURL});	

uploader.on("uploaderReady", setupUploader);
uploader.on("fileselect", fileSelect);
uploader.on("uploadprogress", updateProgress);
uploader.on("uploadcomplete", uploadComplete);
}

Y.on("domready", init);


function setupUploader (event) {
	uploader.set("multiFiles", true);
	uploader.set("simLimit", 3);
	uploader.set("log", true);
	
	var fileFilters = new Array({description:"Images", extensions:"*.jpg;*.png;*.gif"},
	                   {description:"Videos", extensions:"*.avi;*.mov;*.mpg"}); 
	
    uploader.set("fileFilters", fileFilters); 
}

function fileSelect (event) {
	var fileData = event.fileList;	
    
	for (var key in fileData) {
	        if (!selectedFiles[fileData[key].id]) {
			   var output = "<tr><td>" + fileData[key].name + "</td><td>" + 
			                fileData[key].size + "</td><td><div id='div_" + 
			                fileData[key].id + "' class='progressbars'></div></td></tr>";
			   Y.one("#filenames tbody").append(output);
			  
			   var progressBar = new Y.ProgressBar({id:"pb_" + fileData[key].id, layout : '<div class="{labelClass}"></div><div class="{sliderClass}"></div>'});
			       progressBar.render("#div_" + fileData[key].id);
			       progressBar.set("progress", 0);
               
               selectedFiles[fileData[key].id] = true;
			}
	}

}

function updateProgress (event) {
	var pb = Y.Widget.getByNode("#pb_" + event.id);
	pb.set("progress", Math.round(100 * event.bytesLoaded / event.bytesTotal));
}

function uploadComplete (event) {
	var pb = Y.Widget.getByNode("#pb_" + event.id);
	pb.set("progress", 100);
}

function uploadFiles (event) {
	uploader.uploadAll("http://www.yswfblog.com/upload/upload_simple.php");
}

Y.one("#uploadFilesLink").on("click", uploadFiles);

});

</script>