YUI Library Home

Site Search (YDN & YUIBlog):

# YUI Library Examples: Uploader Control (beta): Advanced Uploader Example With Cookie Submission as a POST variable

# Uploader Control (beta): Advanced Uploader Example With Cookie Submission as a POST variable

One of the major limitations of the Flash-based uploader is that it cannot use browser cookies to authenticate file uploads. In this example, we provide sample code that demonstrates how to attach the page cookie as a variable in the body of the upload POST request, rather than in the header. The code will generate a cookie with a username and the last uploaded file name, and send the value along with the file that needs to be uploaded. We also provide a sample backend script that accepts the file upload and echoes the POST variables accompanying the upload (thus ascertaining that the cookie data was received by the server). We show how we can retrieve the data returned by the server and display it to the user.

Note: This is a static example, which means that you will not be able to try it out on our server. You will need to set up the code on your own server in order to run it.

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 the uploader.swf to your server and set the YAHOO.Uploader.SWFURL variable to its full path.

Note: this example is static, which means that it will not work properly on this page. To try it, you will need to download its source code and set it up on your own server. To do so, click "View example in new window", and save the source of that page.

View example in new window.

Select File
Upload File
Progress:
Data returned by the server:

## Advanced Uploader Example With Cookie Submission as a POST variable.

In this example, we demonstrate the code that allows the user to upload a single image or video to the server, and track the upload progress. In addition, the code will also send a generated document cookie along with the request. Since Flash cannot include the browser cookie in the header, the cookie will be attached as a POST variable. The sample server script provided at the end of this example will respond to the request, demonstrating that the cookie was received.

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.

Just as in the other advanced example, we will use regular HTML links as the UI, and modify their background color when the mouse is hovered over them.

<style> #selectFilesLink a, #uploadFilesLink a, #clearFilesLink a { color: #0000CC; background-color: #FFFFFF; } #selectFilesLink a:visited, #uploadFilesLink a:visited, #clearFilesLink a:visited { color: #0000CC; background-color: #FFFFFF; } #uploadFilesLink a:hover, #clearFilesLink a:hover { color: #FFFFFF; background-color: #000000; } </style>

In addition to the controls, we'll also include the following elements: a `messageContainer` div as a container for messages we'll relay to the user, a `selectedFileDisplay` text field to show the name of the file selected for upload, a `progressReport` text field for showing the upload progress, and a `returnedDataDisplay` container with a text area to display the response received from the server: <div id="uiElements" style="display:inline;"> <div id="messageContainer"></div><br/> <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 File</a></div> </div> <div id="uploadFilesLink"><a id="uploadLink" onClick="upload(); return false;" href="#">Upload File</a></div><br/> <div id="selectedFileDisplay"> Progress: <input type="text" cols="50" id="progressReport" value="" readonly /><br/><br/> </div> <div id="returnedDataDisplay"> Data returned by the server:<br/> <textarea id="serverData" rows="15" cols="50" readonly="yes"></textarea> </div> </div>

When the DOM is in a usable state, the `init()` function will check the existing document cookie value to decide what to show in the `messageContainer` (see YAHOO.util.Event.onDOMReady for the `onDOMReady` event). In a standard scenario, the cookie will be set by the server in the header of the loaded page. In our case, for the example's sake, (YUI Cookie Utililty will be used to create and manipulate the example subcookies ("username" and "lastUploadedFile"). If the current Cookie("myCookie") does not have the matching subcookies in it, the `messageContainer` will display a UI allowing the user to set a custom username. In a case where the subcookies already exist, the `messageContainer` div will show a welcome message with the name of the file last uploaded by the user, and a `"Remove User"` button that will remove the username and the last uploaded file name from the document cookie.

function init() { var curCookie = YAHOO.util.Cookie.get("myCookie"); var messageContainer = document.getElementById("messageContainer"); var newHtml; var currentUser = YAHOO.util.Cookie.getSub("myCookie","currentUser"); var lastUploadedFile = YAHOO.util.Cookie.getSub("myCookie","lastUploadedFile"); if(curCookie == null || currentUser == null) { // If there is no existing cookie or username, we will show the text input and button to add the username into cookie. YAHOO.util.Cookie.set("myCookie", document.cookie); newHtml = 'Hi, there. Add your name in the box below.<br/>'; newHtml +='<input type="text" id="userInput" value="Anonymous" /><input type="button" value="Set User" id="btnAdd" />'; }else{ // If there is an existing cookie, we will show a welcome message with an option of removing the username and file name from the cookie. newHtml = currentUser+', welcome back!<br/>'; if(lastUploadedFile) { newHtml += 'Your last uploaded file was '+lastUploadedFile+'<br/>'; } newHtml +='<input type="button" value="Remove User" id="btnRemove" />'; }; messageContainer.innerHTML = newHtml; // reset progressReport and serverData feild. this.serverData = document.getElementById("serverData"); this.serverData.value = ""; this.progressReport = document.getElementById("progressReport"); this.progressReport.value =""; }); YAHOO.util.Event.onDOMReady(init);

Next, we'll add the code to actually modify the cookie based on the input from the user:

// Button Event: "Set User" button clicked. Will add the username to the cookie. YAHOO.util.Event.on("btnAdd", "click", function(){ var newUser = document.getElementById("userInput").value; YAHOO.util.Cookie.setSub("myCookie","currentUser",newUser); var newHtml = "Hi, "+ newUser+"!"; var messageContainer = document.getElementById("messageContainer"); messageContainer.innerHTML = newHtml; }); // Button Event: "Remove User" button clicked. Will remove username and last Uploaded File name from the cookie. YAHOO.util.Event.on("btnRemove", "click", function(){ YAHOO.util.Cookie.removeSub("myCookie","currentUser"); YAHOO.util.Cookie.removeSub("myCookie","lastUploadedFile"); init(); });

To record the name of the uploaded file, we set the variable named "fileName" on uploader's `fileSelect` event.

var fileName; function onFileSelect(event) { for (var file in event.fileList) { if(YAHOO.lang.hasOwnProperty(event.fileList, file)) { fileID = event.fileList[file].id; } } this.progressReport = document.getElementById("progressReport"); fileName = event.fileList[fileID].name; this.progressReport.value = "Selected " + fileName }

After the file upload is complete, we'll store the name of the uploaded file in the subcookie.

// Report back to the user that the upload has completed. function onUploadComplete(event) { YAHOO.util.Cookie.setSub("myCookie", "lastUploadedFile", fileName); this.progressReport.value = "Upload complete."; }

If the `fileID` variable has been populated, we will upload the file to the designated location. Note that we are passing the document cookie as a POST variable in the upload. Important: make sure that the domain of the server that the cookie is being sent to is in the same security sandbox as the domain from which the page hosting the upload dialog has originated. In a simplest scenario, this means that the upload server domain should be the same as the page's domain. That would ensure that the cookie content remains secure.

function upload() { if (fileID != null) { var docCookie = YAHOO.util.Cookie.get("myCookie"); uploader.upload(fileID, "DOMAIN_SAME_AS_PAGE_DOMAIN/upload.php", "POST", {cookieVar:docCookie }); } }

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

function onUploadResponse(event) { this.serverData = document.getElementById("serverData"); this.serverData.value = event.data; }

In PHP, where you would normally check for the cookie value by checking the global `$_COOKIE` array, you can instead check the POST variable that was used to carry the cookie. So, if the cookie is sent as a "cookieVar" parameter (as in the example above), instead of checking for:

$_COOKIE['username'];

you would check for:

$_POST['cookieVar']['username'];

A sample PHP code for retrieving the uploaded file might look as follows (this code does not perform any authentication; you would need to check the cookie as described above to do so):

$target_path = "uploads/"; $target_path = $target_path . basename( $_FILES['Filedata']['name']); if(move_uploaded_file($_FILES['Filedata']['tmp_name'], $target_path)) { echo "The file ".basename( $_FILES['Filedata']['name'])." has been uploaded\n"; echo "POST:\n"; foreach($_POST as $key => $value) echo $key."=".htmlentities($value)."\n"; echo "GET:\n"; foreach($_GET as $key => $value) echo $key."=".htmlentities($value)."\n"; } else { echo "There was an error uploading the file, please try again!"; }

## 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:

### Uploader Control (beta) Examples:

### More Uploader Control (beta) Resources:

- User's Guide (external)
- API Documentation
- Cheat Sheet PDF (external)

Copyright © 2010 Yahoo! Inc. All rights reserved.

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