Advanced Uploader Example With Cookie Submission as a POST variable
<!--
Software License Agreement (BSD License)
Copyright (c) 2009, Yahoo! Inc.
All rights reserved.
Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Yahoo! Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of Yahoo! Inc.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Sources of Intellectual Property Included in the YUI Library
YUI is issued by Yahoo! under the BSD license above. Below is a list of certain publicly available software that is the source of intellectual property in YUI, along with the licensing terms that pertain to thosesources of IP. This list is for informational purposes only and is not intended to represent an exhaustive list of third party contributions to the YUI.
* Douglas Crockford's JSON parsing and stringifying methods: In the JSON Utility, Douglas Crockford's JSON parsing and stringifying methods are adapted from work published at JSON.org. The adapted work is in the public domain.
* Robert Penner's animation-easing algorithms: In the Animation Utility, YUI makes use of Robert Penner's algorithms for easing.
* Geoff Stearns's SWFObject: In the Charts Control and the Uploader versions through 2.7.0, YUI makes use of Geoff Stearns's SWFObject v1.5 for Flash Player detection and embedding. More information on SWFObject can be found here (http://blog.deconcept.com/swfobject/). SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License (http://www.opensource.org/licenses/mit-license.php).
* Diego Perini's IEContentLoaded technique: The Event Utility employs a technique developed by Diego Perini and licensed under GPL. YUI's use of this technique is included under our BSD license with the author's permission.
-->
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Advanced Uploader Example With Cookie Submission as a POST variable</title>
<style type="text/css">
/*margin and padding on body element
can introduce errors in determining
element position and are not recommended;
we turn them off as a foundation for YUI
CSS treatments. */
body {
margin:0;
padding:0;
}
</style>
<link rel="stylesheet" type="text/css" href="yui_2.7.0b-lib/fonts/fonts-min.css" />
<script type="text/javascript" src="yui_2.7.0b-lib/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="yui_2.7.0b-lib/element/element-min.js"></script>
<script type="text/javascript" src="yui_2.7.0b-lib/uploader/uploader.js"></script>
<script type="text/javascript" src="yui_2.7.0b-lib/cookie/cookie-min.js"></script>
<!--there is no custom header content for this example-->
</head>
<body class=" yui-skin-sam">
<h1>Advanced Uploader Example With Cookie Submission as a POST variable</h1>
<div class="exampleIntro">
<p>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.</p>
<p><strong>Note:</strong> 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.</p>
<p><strong>Note:</strong> The YUI Uploader Control requires Flash Player 9.0.45 or higher. The latest version of Flash Player is available at the <a href="http://www.adobe.com/go/getflashplayer">Adobe Flash Player Download Center</a>.</p>
<p><strong>Note:</strong> 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.</p>
<p><strong>Note: </strong>this example is <strong>static</strong>, 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.</p>
</div>
<!--BEGIN SOURCE CODE FOR EXAMPLE -->
<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>
<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>
<script type="text/javascript">
// init messageContainer.
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, this wiil show the text input and a button to add user name to the 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, this wiil show 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 ="";
};
// when DOM is ready, call init().
YAHOO.util.Event.onDOMReady(init);
// Button Event: "Set User" button clicked. Adds 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. Removes 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();
});
YAHOO.util.Event.onDOMReady(function () {
var uiLayer = YAHOO.util.Dom.getRegion('selectLink');
var overlay = YAHOO.util.Dom.get('uploaderOverlay');
YAHOO.util.Dom.setStyle(overlay, 'width', uiLayer.right-uiLayer.left + "px");
YAHOO.util.Dom.setStyle(overlay, 'height', uiLayer.bottom-uiLayer.top + "px");
});
// Custom URL for the uploader swf file (same folder).
YAHOO.widget.Uploader.SWFURL = "yui_2.7.0b-assets/uploader-assets/uploader.swf";
// Instantiate the uploader and write it to its placeholder div.
var uploader = new YAHOO.widget.Uploader( "uploaderOverlay" );
// 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);
uploader.addListener('rollOver', handleRollOver);
uploader.addListener('rollOut', handleRollOut);
uploader.addListener('click', handleClick);
// Variable for holding the selected file id.
var fileID;
// Variable for holding the selected file name.
var fileName;
// When the mouse rolls over the uploader, this function
// is called in response to the rollOver event.
// It changes the appearance of the UI element below the Flash overlay.
function handleRollOver () {
YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('selectLink'), 'color', "#FFFFFF");
YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('selectLink'), 'background-color', "#000000");
}
// On rollOut event, this function is called, which changes the appearance of the
// UI element below the Flash layer back to its original state.
function handleRollOut () {
YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('selectLink'), 'color', "#0000CC");
YAHOO.util.Dom.setStyle(YAHOO.util.Dom.get('selectLink'), 'background-color', "#FFFFFF");
}
// When the Flash layer is clicked, the "Browse" dialog is invoked.
// The click event handler allows you to do something else if you need to.
function handleClick () {
}
// When contentReady event is fired, you can call methods on the uploader.
function handleContentReady () {
// Allows the uploader to send log messages to trace, as well as to YAHOO.log
uploader.setAllowLogging(true);
// Disallows multiple file selection in "Browse" dialog.
uploader.setAllowMultipleFiles(false);
// New set of file filters.
var ff = new Array({description:"Images", extensions:"*.jpg;*.png;*.gif"},
{description:"Videos", extensions:"*.avi;*.mov;*.mpg"});
// Apply new set of file filters to the uploader.
uploader.setFileFilters(ff);
}
// Actually uploads the files. Since we are only allowing one file
// to be selected, we use the upload function, in conjunction with the id
// of the selected file (returned by the fileSelect event). We are also including
// the cookie as a variable.
function upload() {
if (fileID != null) {
var docCookie = YAHOO.util.Cookie.get("myCookie");
uploader.upload(fileID, "YOUR_DOMAIN_SAME_AS_PAGE_DOMAIN_HERE",
"POST",
{cookieVar:docCookie });
}
}
// Fired when the user selects files in the "Browse" dialog
// and clicks "Ok". Here, we set the value of the progress
// report textfield to reflect the fact that a file has been
// selected.
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
}
// When the upload starts, we inform the user about it via
// the progress report textfield.
function onUploadStart(event) {
this.progressReport.value = "Starting upload...";
}
// As upload progresses, we report back to the user via the
// progress report textfield.
function onUploadProgress(event) {
prog = Math.round(100*(event["bytesLoaded"]/event["bytesTotal"]));
this.progressReport.value = prog + "% uploaded...";
}
// 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.";
}
// Report back to the user if there has been an error.
function onUploadError(event) {
this.progressReport.value = "Upload error.";
}
// Do something if an upload is canceled.
function onUploadCancel(event) {
}
// When the data is received back from the server, display it to the user
// in the server data text area.
function onUploadResponse(event) {
this.serverData = document.getElementById("serverData");
this.serverData.value = event.data;
}
</script>
<!--END SOURCE CODE FOR EXAMPLE -->
</body>
yui_2.7.0b.zip( 4,431 k)Related examples in the same category