YUI Library Home

YUI Library Examples: Uploader Control (beta): Advanced Uploader Example With Additional POST Variables and Server Data Return

Uploader Control (beta): Advanced Uploader Example With Additional POST Variables and Server Data Return

This example demonstrates how the YUI Uploader Control can be rendered as a transparent layer on top of your own UI and how custom variables can be added to the upload's POST request. In this example, the server-side script also echoes the POST variables accompanying the upload; we retrieve the data returned by the server and display it to the user.

Note: The YUI Uploader Control requires Flash Player 9.0.45 or higher. The latest version of Flash Player is available at the Adobe Flash Player Download Center.

Note: The YUI Uploader Control requires the uploader.swf Flash file that is distributed as part of the YUI package, in the uploader/assets folder. Copy uploader.swf to your server and set the YAHOO.Uploader.SWFURL variable to its full path.

Note: This example uses a server-side script to accept file uploads. The script used does not open or store the file data sent to it. It also does not store the accompanying POST variables, but it does echo them in the response relayed back to the sender of the request. When trying out the example, do not send any sensitive or private data. Do not exceed a file size of 10 MB.

Set custom values for a couple POST vars:
var1:
var2:


Progress:

Data returned by the server:

Advanced Uploader Example With Additional POST Variables and Server Data Return

In this example, we allow the user to select a single image or video, and upload it to the server, while tracking progress on the upload. The user can specify custom values for a couple POST vars sent along with the upload, and also get the response from the server (in this case, a simple echo of POSTed variables). Because of security changes in Flash Player 10, the UI for invoking the "Browse" dialog has to be contained within the Flash player. In this example, the Flash player is rendered as a transparent overlay on top of a custom HTML-based UI. The Uploader running in the Flash player dispatches necessary mouse events to the DOM to make visual changes to the overlaid UI.

For starters, let's define the necessary UI styles. We will use regular text links as the UI, and switch their background color when the mouse hovers over them.

1<style> 
2#selectFilesLink a, #uploadFilesLink a, #clearFilesLink a { 
3    color: #0000CC; 
4    background-color: #FFFFFF; 
5
6 
7#selectFilesLink a:visited, #uploadFilesLink a:visited, #clearFilesLink a:visited { 
8    color: #0000CC; 
9    background-color: #FFFFFF; 
10
11 
12#uploadFilesLink a:hover, #clearFilesLink a:hover {  
13    color: #FFFFFF; 
14    background-color: #000000; 
15
16</style> 
view plain | print | ?

Next, we'll place the UI elements on the page. Notice that the selectFilesLink div is overlaid by the uploaderOverlay div. uploaderOverlay is where we'll place the transparent Flash UI layer, that will dispatch various mouse events, based on which we will be able to change the appearance of the UI below.

We are also placing a few input fields for the user to specify two custom POST variables that will be sent along with the file upload, as well as a text field to report back on the upload progress, and a text area to display the response received from the server:

1<div id="uiElements" style="display:inline;"
2        <div id="postVars"
3        Set custom values for a couple POST vars:<br/> 
4        var1: <input type="text" id="var1Value" value="var1 default value" /><br/> 
5        var2: <input type="text" id="var2Value" value="var2 default value" /><br/><br/> 
6        </div> 
7        <div id="uploaderContainer"
8            <div id="uploaderOverlay" style="position:absolute; z-index:2"></div> 
9            <div id="selectFilesLink" style="z-index:1"><id="selectLink" href="#">Select File</a></div
10        </div> 
11        <div id="uploadFilesLink"><id="uploadLink" onClick="upload(); return false;" href="#">Upload File</a></div><br/> 
12        <div id="selectedFileDisplay"
13        Progress: <input type="text" cols="50" id="progressReport" value="" readonly /><br/><br/> 
14        </div> 
15        <div id="returnedDataDisplay"
16        Data returned by the server:<br/> 
17        <textarea id="serverData" rows="5" cols="50"></textarea> 
18        </div> 
19</div> 
view plain | print | ?

Once the DOM is ready, we can size our container for the transparent UI to the link below it. The following code accomplishes that:

1<script type="text/javascript"
2YAHOO.util.Event.onDOMReady(function () {  
3var uiLayer = YAHOO.util.Dom.getRegion('selectLink'); 
4var overlay = YAHOO.util.Dom.get('uploaderOverlay'); 
5YAHOO.util.Dom.setStyle(overlay, 'width', uiLayer.right-uiLayer.left + "px"); 
6YAHOO.util.Dom.setStyle(overlay, 'height', uiLayer.bottom-uiLayer.top + "px"); 
7}); 
view plain | print | ?

Now we can instantiate the uploader and place it in the container div.

1YAHOO.widget.Uploader.SWFURL = "assets/uploader.swf"
2var uploader = new YAHOO.widget.Uploader( "uploaderOverlay" ); 
view plain | print | ?

We add handler functions to the uploader events. Note that methods on the uploader should not be called until the "contentReady" event has fired:

1uploader.addListener('contentReady', handleContentReady); 
2uploader.addListener('fileSelect', onFileSelect) 
3uploader.addListener('uploadStart', onUploadStart); 
4uploader.addListener('uploadProgress', onUploadProgress); 
5uploader.addListener('uploadCancel', onUploadCancel); 
6uploader.addListener('uploadComplete', onUploadComplete); 
7uploader.addListener('uploadCompleteData', onUploadResponse); 
8uploader.addListener('uploadError', onUploadError); 
9uploader.addListener('rollOver', handleRollOver); 
10uploader.addListener('rollOut', handleRollOut); 
11uploader.addListener('click', handleClick); 
view plain | print | ?

These handlers are called when the mouse rolls over and out of the uploader, respectively. They modify the appearance of the UI layer under the transparent Flash layer to match the behavior of the rest of the UI.

1function handleRollOver () { 
2    YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('selectLink'), 'color'"#FFFFFF"); 
3    YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('selectLink'), 'background-color'"#000000"); 
4
5 
6function handleRollOut () { 
7    YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('selectLink'), 'color'"#0000CC"); 
8    YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('selectLink'), 'background-color'"#FFFFFF"); 
9
10 
11function handleClick () { 
12
view plain | print | ?

Once the contentReady event has fired, we can configure the uploader. In this case, we call a function that turns on logging (so that everything we do is reflected in the YUI logger, as well as in the Flash trace file), disallow multiple file selection, and define a set of filters on the file extensions that the user can choose.

1function handleContentReady () { 
2    uploader.setAllowLogging(true); 
3    uploader.setAllowMultipleFiles(false); 
4 
5    var ff = new Array({description:"Images", extensions:"*.jpg;*.png;*.gif"}, 
6                       {description:"Videos", extensions:"*.avi;*.mov;*.mpg"}); 
7 
8    uploader.setFileFilters(ff); 
9
view plain | print | ?

The upload function is called when "Upload Files" link is clicked. It checks whether the fileID variable has been populated, and if so, instructs the upload to send that file to the specified location. Note that we are overriding the default value for the variable submission method (default is "GET", we are making it "POST"). We are also passing an object with two POST variables to submit along with the upload; in this case, their values come from input fields that were presented to the user.

1function upload() { 
2if (fileID != null) { 
3    uploader.upload(fileID, "http://www.yswfblog.com/upload/upload.php",  
4                    "POST",  
5                    {var1:document.getElementById("var1Value").value, 
6                     var2:document.getElementById("var2Value").value}); 
7}    
8
view plain | print | ?

The fileID variable that the upload() function checked for needs to be defined and populated. This happens in the fileSelect event handler, that looks at the list of files passed in the event (they are indexed by the file id, rather than by numerical index, and so an iterator is necessary). Since we know the list will contain only one file, we can simply assign that file id to the fileID variable.

We also update the progress report text field with the information on the selected file

1var fileID; 
2 
3function onFileSelect(event) { 
4        for (var file in event.fileList) { 
5            if(YAHOO.lang.hasOwnProperty(event.fileList, file)) { 
6                fileID = event.fileList[file].id; 
7            } 
8        } 
9 
10    this.progressReport = document.getElementById("progressReport"); 
11    this.progressReport.value = "Selected " + event.fileList[fileID].name; 
12
view plain | print | ?

Update the progress report when the upload starts:

1function onUploadStart(event) { 
2    this.progressReport.value = "Starting upload..."
3
view plain | print | ?

Update the progress report on upload progress events:

1function onUploadProgress(event) { 
2    prog = Math.round(100*(event["bytesLoaded"]/event["bytesTotal"])); 
3    this.progressReport.value = prog + "% uploaded..."
4
view plain | print | ?

Update the progress report on upload complete event:

1function onUploadComplete(event) { 
2    this.progressReport.value = "Upload complete."
3
view plain | print | ?

Update the progress report in case of an upload error:

1function onUploadError(event) { 
2    this.progressReport.value = "Upload error."
3
view plain | print | ?

When a response is received from the server, display it in the provided text area:

1    function onUploadResponse(event) { 
2        this.serverData = document.getElementById("serverData"); 
3        this.serverData.value = event.data; 
4    } 
5</script> 
view plain | print | ?

Configuration for This Example

You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.

YUI Logger Output:

Logger Console

INFO 56ms (+51) 8:49:01 PM:

LogReader instance0

LogReader initialized

INFO 5ms (+5) 8:49:01 PM:

global

Unable to load SWF assets/uploader.swf

INFO 0ms (+0) 8:49:01 PM:

global

Logger initialized

More Uploader Control (beta) Resources:

Copyright © 2010 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings