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.
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.
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 | ? |
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:
1 | <div id="uiElements" style="display:inline;"> |
2 | |
3 | <div id="messageContainer"></div><br/> |
4 | <div id="uploaderContainer"> |
5 | <div id="uploaderOverlay" style="position:absolute; z-index:2"></div> |
6 | <div id="selectFilesLink" style="z-index:1"><a id="selectLink" href="#">Select File</a></div> |
7 | </div> |
8 | <div id="uploadFilesLink"><a id="uploadLink" onClick="upload(); return false;" href="#">Upload File</a></div><br/> |
9 | <div id="selectedFileDisplay"> |
10 | Progress: <input type="text" cols="50" id="progressReport" value="" readonly /><br/><br/> |
11 | </div> |
12 | <div id="returnedDataDisplay"> |
13 | Data returned by the server:<br/> |
14 | |
15 | <textarea id="serverData" rows="15" cols="50" readonly="yes"></textarea> |
16 | </div> |
17 | </div> |
view plain | print | ? |
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.
1 | function init() { |
2 | var curCookie = YAHOO.util.Cookie.get("myCookie"); |
3 | var messageContainer = document.getElementById("messageContainer"); |
4 | var newHtml; |
5 | var currentUser = YAHOO.util.Cookie.getSub("myCookie","currentUser"); |
6 | var lastUploadedFile = YAHOO.util.Cookie.getSub("myCookie","lastUploadedFile"); |
7 | |
8 | if(curCookie == null || currentUser == null) { |
9 | // If there is no existing cookie or username, we will show the text input and button to add the username into cookie. |
10 | YAHOO.util.Cookie.set("myCookie", document.cookie); |
11 | newHtml = 'Hi, there. Add your name in the box below.<br/>'; |
12 | newHtml +='<input type="text" id="userInput" value="Anonymous" /><input type="button" value="Set User" id="btnAdd" />'; |
13 | }else{ |
14 | // 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. |
15 | newHtml = currentUser+', welcome back!<br/>'; |
16 | if(lastUploadedFile) { |
17 | newHtml += 'Your last uploaded file was '+lastUploadedFile+'<br/>'; |
18 | } |
19 | newHtml +='<input type="button" value="Remove User" id="btnRemove" />'; |
20 | }; |
21 | messageContainer.innerHTML = newHtml; |
22 | |
23 | // reset progressReport and serverData feild. |
24 | this.serverData = document.getElementById("serverData"); |
25 | this.serverData.value = ""; |
26 | |
27 | this.progressReport = document.getElementById("progressReport"); |
28 | this.progressReport.value =""; |
29 | }); |
30 | |
31 | YAHOO.util.Event.onDOMReady(init); |
view plain | print | ? |
Next, we'll add the code to actually modify the cookie based on the input from the user:
1 | // Button Event: "Set User" button clicked. Will add the username to the cookie. |
2 | YAHOO.util.Event.on("btnAdd", "click", function(){ |
3 | var newUser = document.getElementById("userInput").value; |
4 | YAHOO.util.Cookie.setSub("myCookie","currentUser",newUser); |
5 | var newHtml = "Hi, "+ newUser+"!"; |
6 | var messageContainer = document.getElementById("messageContainer"); |
7 | messageContainer.innerHTML = newHtml; |
8 | }); |
9 | |
10 | // Button Event: "Remove User" button clicked. Will remove username and last Uploaded File name from the cookie. |
11 | YAHOO.util.Event.on("btnRemove", "click", function(){ |
12 | YAHOO.util.Cookie.removeSub("myCookie","currentUser"); |
13 | YAHOO.util.Cookie.removeSub("myCookie","lastUploadedFile"); |
14 | init(); |
15 | }); |
view plain | print | ? |
To record the name of the uploaded file, we set the variable named "fileName" on uploader's fileSelect
event.
1 | var fileName; |
2 | |
3 | function 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 | fileName = event.fileList[fileID].name; |
12 | this.progressReport.value = "Selected " + fileName |
13 | } |
view plain | print | ? |
After the file upload is complete, we'll store the name of the uploaded file in the subcookie.
1 | // Report back to the user that the upload has completed. |
2 | function onUploadComplete(event) { |
3 | YAHOO.util.Cookie.setSub("myCookie", "lastUploadedFile", fileName); |
4 | this.progressReport.value = "Upload complete."; |
5 | } |
view plain | print | ? |
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.
1 | function upload() { |
2 | |
3 | if (fileID != null) { |
4 | var docCookie = YAHOO.util.Cookie.get("myCookie"); |
5 | uploader.upload(fileID, "DOMAIN_SAME_AS_PAGE_DOMAIN/upload.php", |
6 | "POST", |
7 | {cookieVar:docCookie }); |
8 | } |
9 | } |
10 | |
view plain | print | ? |
When a response is received from the server, we display it in the provided text area:
1 | function onUploadResponse(event) { |
2 | this.serverData = document.getElementById("serverData"); |
3 | this.serverData.value = event.data; |
4 | } |
view plain | print | ? |
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:
1 | $_COOKIE['username']; |
view plain | print | ? |
1 | $_POST['cookieVar']['username']; |
view plain | print | ? |
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):
1 | $target_path = "uploads/"; |
2 | |
3 | $target_path = $target_path . basename( $_FILES['Filedata']['name']); |
4 | |
5 | if(move_uploaded_file($_FILES['Filedata']['tmp_name'], $target_path)) { |
6 | echo "The file ".basename( $_FILES['Filedata']['name'])." has been uploaded\n"; |
7 | echo "POST:\n"; |
8 | foreach($_POST as $key => $value) echo $key."=".htmlentities($value)."\n"; |
9 | echo "GET:\n"; |
10 | foreach($_GET as $key => $value) echo $key."=".htmlentities($value)."\n"; |
11 | } else { |
12 | echo "There was an error uploading the file, please try again!"; |
13 | } |
view plain | print | ? |
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.
INFO 0ms (+0) 4:11:03 PM:
global
Logger initialized
Copyright © 2009 Yahoo! Inc. All rights reserved.
Privacy Policy - Terms of Service - Copyright Policy - Job Openings