Upgrade to ExtJS 3.0.0 - Released 07/06/2009
[extjs.git] / docs / source / swfupload.html
1 <html>\r
2 <head>\r
3   <title>The source code</title>\r
4     <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />\r
5     <script type="text/javascript" src="../resources/prettify/prettify.js"></script>\r
6 </head>\r
7 <body  onload="prettyPrint();">\r
8     <pre class="prettyprint lang-js"><div id="prop-Ext.ux.TaskBar.TaskButton-Constructor"></div>/**\r
9  * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com\r
10  *\r
11  * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/,  http://www.vinterwebb.se/\r
12  *\r
13  * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilz�n and Mammon Media and is released under the MIT License:\r
14  * http://www.opensource.org/licenses/mit-license.php\r
15  *\r
16  * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:\r
17  * http://www.opensource.org/licenses/mit-license.php\r
18  *\r
19  */\r
20 \r
21 \r
22 /* ******************* */\r
23 /* Constructor & Init  */\r
24 /* ******************* */\r
25 var SWFUpload;\r
26 \r
27 if (SWFUpload == undefined) {\r
28         SWFUpload = function (settings) {\r
29                 this.initSWFUpload(settings);\r
30         };\r
31 }\r
32 \r
33 SWFUpload.prototype.initSWFUpload = function (settings) {\r
34         try {\r
35                 this.customSettings = {};       // A container where developers can place their own settings associated with this instance.\r
36                 this.settings = settings;\r
37                 this.eventQueue = [];\r
38                 this.movieName = "SWFUpload_" + SWFUpload.movieCount++;\r
39                 this.movieElement = null;\r
40 \r
41 \r
42                 // Setup global control tracking\r
43                 SWFUpload.instances[this.movieName] = this;\r
44 \r
45                 // Load the settings.  Load the Flash movie.\r
46                 this.initSettings();\r
47                 this.loadFlash();\r
48                 this.displayDebugInfo();\r
49         } catch (ex) {\r
50                 delete SWFUpload.instances[this.movieName];\r
51                 throw ex;\r
52         }\r
53 };\r
54 \r
55 /* *************** */\r
56 /* Static Members  */\r
57 /* *************** */\r
58 SWFUpload.instances = {};\r
59 SWFUpload.movieCount = 0;\r
60 SWFUpload.version = "2.2.0 2009-03-25";\r
61 SWFUpload.QUEUE_ERROR = {\r
62         QUEUE_LIMIT_EXCEEDED                    : -100,\r
63         FILE_EXCEEDS_SIZE_LIMIT                 : -110,\r
64         ZERO_BYTE_FILE                                  : -120,\r
65         INVALID_FILETYPE                                : -130\r
66 };\r
67 SWFUpload.UPLOAD_ERROR = {\r
68         HTTP_ERROR                                              : -200,\r
69         MISSING_UPLOAD_URL                      : -210,\r
70         IO_ERROR                                                : -220,\r
71         SECURITY_ERROR                                  : -230,\r
72         UPLOAD_LIMIT_EXCEEDED                   : -240,\r
73         UPLOAD_FAILED                                   : -250,\r
74         SPECIFIED_FILE_ID_NOT_FOUND             : -260,\r
75         FILE_VALIDATION_FAILED                  : -270,\r
76         FILE_CANCELLED                                  : -280,\r
77         UPLOAD_STOPPED                                  : -290\r
78 };\r
79 SWFUpload.FILE_STATUS = {\r
80         QUEUED           : -1,\r
81         IN_PROGRESS      : -2,\r
82         ERROR            : -3,\r
83         COMPLETE         : -4,\r
84         CANCELLED        : -5\r
85 };\r
86 SWFUpload.BUTTON_ACTION = {\r
87         SELECT_FILE  : -100,\r
88         SELECT_FILES : -110,\r
89         START_UPLOAD : -120\r
90 };\r
91 SWFUpload.CURSOR = {\r
92         ARROW : -1,\r
93         HAND : -2\r
94 };\r
95 SWFUpload.WINDOW_MODE = {\r
96         WINDOW : "window",\r
97         TRANSPARENT : "transparent",\r
98         OPAQUE : "opaque"\r
99 };\r
100 \r
101 // Private: takes a URL, determines if it is relative and converts to an absolute URL\r
102 // using the current site. Only processes the URL if it can, otherwise returns the URL untouched\r
103 SWFUpload.completeURL = function(url) {\r
104         if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) {\r
105                 return url;\r
106         }\r
107         \r
108         var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");\r
109         \r
110         var indexSlash = window.location.pathname.lastIndexOf("/");\r
111         if (indexSlash <= 0) {\r
112                 path = "/";\r
113         } else {\r
114                 path = window.location.pathname.substr(0, indexSlash) + "/";\r
115         }\r
116         \r
117         return /*currentURL +*/ path + url;\r
118         \r
119 };\r
120 \r
121 \r
122 /* ******************** */\r
123 /* Instance Members  */\r
124 /* ******************** */\r
125 \r
126 // Private: initSettings ensures that all the\r
127 // settings are set, getting a default value if one was not assigned.\r
128 SWFUpload.prototype.initSettings = function () {\r
129         this.ensureDefault = function (settingName, defaultValue) {\r
130                 this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];\r
131         };\r
132         \r
133         // Upload backend settings\r
134         this.ensureDefault("upload_url", "");\r
135         this.ensureDefault("preserve_relative_urls", false);\r
136         this.ensureDefault("file_post_name", "Filedata");\r
137         this.ensureDefault("post_params", {});\r
138         this.ensureDefault("use_query_string", false);\r
139         this.ensureDefault("requeue_on_error", false);\r
140         this.ensureDefault("http_success", []);\r
141         this.ensureDefault("assume_success_timeout", 0);\r
142         \r
143         // File Settings\r
144         this.ensureDefault("file_types", "*.*");\r
145         this.ensureDefault("file_types_description", "All Files");\r
146         this.ensureDefault("file_size_limit", 0);       // Default zero means "unlimited"\r
147         this.ensureDefault("file_upload_limit", 0);\r
148         this.ensureDefault("file_queue_limit", 0);\r
149 \r
150         // Flash Settings\r
151         this.ensureDefault("flash_url", "swfupload.swf");\r
152         this.ensureDefault("prevent_swf_caching", true);\r
153         \r
154         // Button Settings\r
155         this.ensureDefault("button_image_url", "");\r
156         this.ensureDefault("button_width", 1);\r
157         this.ensureDefault("button_height", 1);\r
158         this.ensureDefault("button_text", "");\r
159         this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");\r
160         this.ensureDefault("button_text_top_padding", 0);\r
161         this.ensureDefault("button_text_left_padding", 0);\r
162         this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);\r
163         this.ensureDefault("button_disabled", false);\r
164         this.ensureDefault("button_placeholder_id", "");\r
165         this.ensureDefault("button_placeholder", null);\r
166         this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);\r
167         this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);\r
168         \r
169         // Debug Settings\r
170         this.ensureDefault("debug", false);\r
171         this.settings.debug_enabled = this.settings.debug;      // Here to maintain v2 API\r
172         \r
173         // Event Handlers\r
174         this.settings.return_upload_start_handler = this.returnUploadStart;\r
175         this.ensureDefault("swfupload_loaded_handler", null);\r
176         this.ensureDefault("file_dialog_start_handler", null);\r
177         this.ensureDefault("file_queued_handler", null);\r
178         this.ensureDefault("file_queue_error_handler", null);\r
179         this.ensureDefault("file_dialog_complete_handler", null);\r
180         \r
181         this.ensureDefault("upload_start_handler", null);\r
182         this.ensureDefault("upload_progress_handler", null);\r
183         this.ensureDefault("upload_error_handler", null);\r
184         this.ensureDefault("upload_success_handler", null);\r
185         this.ensureDefault("upload_complete_handler", null);\r
186         \r
187         this.ensureDefault("debug_handler", this.debugMessage);\r
188 \r
189         this.ensureDefault("custom_settings", {});\r
190 \r
191         // Other settings\r
192         this.customSettings = this.settings.custom_settings;\r
193         \r
194         // Update the flash url if needed\r
195         if (!!this.settings.prevent_swf_caching) {\r
196                 this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();\r
197         }\r
198         \r
199         if (!this.settings.preserve_relative_urls) {\r
200                 //this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url);     // Don't need to do this one since flash doesn't look at it\r
201                 this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);\r
202                 this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);\r
203         }\r
204         \r
205         delete this.ensureDefault;\r
206 };\r
207 \r
208 // Private: loadFlash replaces the button_placeholder element with the flash movie.\r
209 SWFUpload.prototype.loadFlash = function () {\r
210         var targetElement, tempParent;\r
211 \r
212         // Make sure an element with the ID we are going to use doesn't already exist\r
213         if (document.getElementById(this.movieName) !== null) {\r
214                 throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";\r
215         }\r
216 \r
217         // Get the element where we will be placing the flash movie\r
218         targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder;\r
219 \r
220         if (targetElement == undefined) {\r
221                 throw "Could not find the placeholder element: " + this.settings.button_placeholder_id;\r
222         }\r
223 \r
224         // Append the container and load the flash\r
225         tempParent = document.createElement("div");\r
226         tempParent.innerHTML = this.getFlashHTML();     // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)\r
227         targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);\r
228 \r
229         // Fix IE Flash/Form bug\r
230         if (window[this.movieName] == undefined) {\r
231                 window[this.movieName] = this.getMovieElement();\r
232         }\r
233         \r
234 };\r
235 \r
236 // Private: getFlashHTML generates the object tag needed to embed the flash in to the document\r
237 SWFUpload.prototype.getFlashHTML = function () {\r
238         // Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay\r
239         return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',\r
240                                 '<param name="wmode" value="', this.settings.button_window_mode, '" />',\r
241                                 '<param name="movie" value="', this.settings.flash_url, '" />',\r
242                                 '<param name="quality" value="high" />',\r
243                                 '<param name="menu" value="false" />',\r
244                                 '<param name="allowScriptAccess" value="always" />',\r
245                                 '<param name="flashvars" value="' + this.getFlashVars() + '" />',\r
246                                 '</object>'].join("");\r
247 };\r
248 \r
249 // Private: getFlashVars builds the parameter string that will be passed\r
250 // to flash in the flashvars param.\r
251 SWFUpload.prototype.getFlashVars = function () {\r
252         // Build a string from the post param object\r
253         var paramString = this.buildParamString();\r
254         var httpSuccessString = this.settings.http_success.join(",");\r
255         \r
256         // Build the parameter string\r
257         return ["movieName=", encodeURIComponent(this.movieName),\r
258                         "&amp;uploadURL=", encodeURIComponent(this.settings.upload_url),\r
259                         "&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string),\r
260                         "&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),\r
261                         "&amp;httpSuccess=", encodeURIComponent(httpSuccessString),\r
262                         "&amp;assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout),\r
263                         "&amp;params=", encodeURIComponent(paramString),\r
264                         "&amp;filePostName=", encodeURIComponent(this.settings.file_post_name),\r
265                         "&amp;fileTypes=", encodeURIComponent(this.settings.file_types),\r
266                         "&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),\r
267                         "&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),\r
268                         "&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),\r
269                         "&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),\r
270                         "&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled),\r
271                         "&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url),\r
272                         "&amp;buttonWidth=", encodeURIComponent(this.settings.button_width),\r
273                         "&amp;buttonHeight=", encodeURIComponent(this.settings.button_height),\r
274                         "&amp;buttonText=", encodeURIComponent(this.settings.button_text),\r
275                         "&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),\r
276                         "&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),\r
277                         "&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),\r
278                         "&amp;buttonAction=", encodeURIComponent(this.settings.button_action),\r
279                         "&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled),\r
280                         "&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor)\r
281                 ].join("");\r
282 };\r
283 \r
284 // Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload\r
285 // The element is cached after the first lookup\r
286 SWFUpload.prototype.getMovieElement = function () {\r
287         if (this.movieElement == undefined) {\r
288                 this.movieElement = document.getElementById(this.movieName);\r
289         }\r
290 \r
291         if (this.movieElement === null) {\r
292                 throw "Could not find Flash element";\r
293         }\r
294         \r
295         return this.movieElement;\r
296 };\r
297 \r
298 // Private: buildParamString takes the name/value pairs in the post_params setting object\r
299 // and joins them up in to a string formatted "name=value&amp;name=value"\r
300 SWFUpload.prototype.buildParamString = function () {\r
301         var postParams = this.settings.post_params; \r
302         var paramStringPairs = [];\r
303 \r
304         if (typeof(postParams) === "object") {\r
305                 for (var name in postParams) {\r
306                         if (postParams.hasOwnProperty(name)) {\r
307                                 paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));\r
308                         }\r
309                 }\r
310         }\r
311 \r
312         return paramStringPairs.join("&amp;");\r
313 };\r
314 \r
315 // Public: Used to remove a SWFUpload instance from the page. This method strives to remove\r
316 // all references to the SWF, and other objects so memory is properly freed.\r
317 // Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.\r
318 // Credits: Major improvements provided by steffen\r
319 SWFUpload.prototype.destroy = function () {\r
320         try {\r
321                 // Make sure Flash is done before we try to remove it\r
322                 this.cancelUpload(null, false);\r
323                 \r
324 \r
325                 // Remove the SWFUpload DOM nodes\r
326                 var movieElement = null;\r
327                 movieElement = this.getMovieElement();\r
328                 \r
329                 if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE\r
330                         // Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround)\r
331                         for (var i in movieElement) {\r
332                                 try {\r
333                                         if (typeof(movieElement[i]) === "function") {\r
334                                                 movieElement[i] = null;\r
335                                         }\r
336                                 } catch (ex1) {}\r
337                         }\r
338 \r
339                         // Remove the Movie Element from the page\r
340                         try {\r
341                                 movieElement.parentNode.removeChild(movieElement);\r
342                         } catch (ex) {}\r
343                 }\r
344                 \r
345                 // Remove IE form fix reference\r
346                 window[this.movieName] = null;\r
347 \r
348                 // Destroy other references\r
349                 SWFUpload.instances[this.movieName] = null;\r
350                 delete SWFUpload.instances[this.movieName];\r
351 \r
352                 this.movieElement = null;\r
353                 this.settings = null;\r
354                 this.customSettings = null;\r
355                 this.eventQueue = null;\r
356                 this.movieName = null;\r
357                 \r
358                 \r
359                 return true;\r
360         } catch (ex2) {\r
361                 return false;\r
362         }\r
363 };\r
364 \r
365 \r
366 // Public: displayDebugInfo prints out settings and configuration\r
367 // information about this SWFUpload instance.\r
368 // This function (and any references to it) can be deleted when placing\r
369 // SWFUpload in production.\r
370 SWFUpload.prototype.displayDebugInfo = function () {\r
371         this.debug(\r
372                 [\r
373                         "---SWFUpload Instance Info---\n",\r
374                         "Version: ", SWFUpload.version, "\n",\r
375                         "Movie Name: ", this.movieName, "\n",\r
376                         "Settings:\n",\r
377                         "\t", "upload_url:               ", this.settings.upload_url, "\n",\r
378                         "\t", "flash_url:                ", this.settings.flash_url, "\n",\r
379                         "\t", "use_query_string:         ", this.settings.use_query_string.toString(), "\n",\r
380                         "\t", "requeue_on_error:         ", this.settings.requeue_on_error.toString(), "\n",\r
381                         "\t", "http_success:             ", this.settings.http_success.join(", "), "\n",\r
382                         "\t", "assume_success_timeout:   ", this.settings.assume_success_timeout, "\n",\r
383                         "\t", "file_post_name:           ", this.settings.file_post_name, "\n",\r
384                         "\t", "post_params:              ", this.settings.post_params.toString(), "\n",\r
385                         "\t", "file_types:               ", this.settings.file_types, "\n",\r
386                         "\t", "file_types_description:   ", this.settings.file_types_description, "\n",\r
387                         "\t", "file_size_limit:          ", this.settings.file_size_limit, "\n",\r
388                         "\t", "file_upload_limit:        ", this.settings.file_upload_limit, "\n",\r
389                         "\t", "file_queue_limit:         ", this.settings.file_queue_limit, "\n",\r
390                         "\t", "debug:                    ", this.settings.debug.toString(), "\n",\r
391 \r
392                         "\t", "prevent_swf_caching:      ", this.settings.prevent_swf_caching.toString(), "\n",\r
393 \r
394                         "\t", "button_placeholder_id:    ", this.settings.button_placeholder_id.toString(), "\n",\r
395                         "\t", "button_placeholder:       ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n",\r
396                         "\t", "button_image_url:         ", this.settings.button_image_url.toString(), "\n",\r
397                         "\t", "button_width:             ", this.settings.button_width.toString(), "\n",\r
398                         "\t", "button_height:            ", this.settings.button_height.toString(), "\n",\r
399                         "\t", "button_text:              ", this.settings.button_text.toString(), "\n",\r
400                         "\t", "button_text_style:        ", this.settings.button_text_style.toString(), "\n",\r
401                         "\t", "button_text_top_padding:  ", this.settings.button_text_top_padding.toString(), "\n",\r
402                         "\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",\r
403                         "\t", "button_action:            ", this.settings.button_action.toString(), "\n",\r
404                         "\t", "button_disabled:          ", this.settings.button_disabled.toString(), "\n",\r
405 \r
406                         "\t", "custom_settings:          ", this.settings.custom_settings.toString(), "\n",\r
407                         "Event Handlers:\n",\r
408                         "\t", "swfupload_loaded_handler assigned:  ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",\r
409                         "\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",\r
410                         "\t", "file_queued_handler assigned:       ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",\r
411                         "\t", "file_queue_error_handler assigned:  ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",\r
412                         "\t", "upload_start_handler assigned:      ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",\r
413                         "\t", "upload_progress_handler assigned:   ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",\r
414                         "\t", "upload_error_handler assigned:      ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",\r
415                         "\t", "upload_success_handler assigned:    ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",\r
416                         "\t", "upload_complete_handler assigned:   ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",\r
417                         "\t", "debug_handler assigned:             ", (typeof this.settings.debug_handler === "function").toString(), "\n"\r
418                 ].join("")\r
419         );\r
420 };\r
421 \r
422 /* Note: addSetting and getSetting are no longer used by SWFUpload but are included\r
423         the maintain v2 API compatibility\r
424 */\r
425 // Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.\r
426 SWFUpload.prototype.addSetting = function (name, value, default_value) {\r
427     if (value == undefined) {\r
428         return (this.settings[name] = default_value);\r
429     } else {\r
430         return (this.settings[name] = value);\r
431         }\r
432 };\r
433 \r
434 // Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.\r
435 SWFUpload.prototype.getSetting = function (name) {\r
436     if (this.settings[name] != undefined) {\r
437         return this.settings[name];\r
438         }\r
439 \r
440     return "";\r
441 };\r
442 \r
443 \r
444 \r
445 // Private: callFlash handles function calls made to the Flash element.\r
446 // Calls are made with a setTimeout for some functions to work around\r
447 // bugs in the ExternalInterface library.\r
448 SWFUpload.prototype.callFlash = function (functionName, argumentArray) {\r
449         argumentArray = argumentArray || [];\r
450         \r
451         var movieElement = this.getMovieElement();\r
452         var returnValue, returnString;\r
453 \r
454         // Flash's method if calling ExternalInterface methods (code adapted from MooTools).\r
455         try {\r
456                 returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');\r
457                 returnValue = eval(returnString);\r
458         } catch (ex) {\r
459                 throw "Call to " + functionName + " failed";\r
460         }\r
461         \r
462         // Unescape file post param values\r
463         if (returnValue != undefined && typeof returnValue.post === "object") {\r
464                 returnValue = this.unescapeFilePostParams(returnValue);\r
465         }\r
466 \r
467         return returnValue;\r
468 };\r
469 \r
470 /* *****************************\r
471         -- Flash control methods --\r
472         Your UI should use these\r
473         to operate SWFUpload\r
474    ***************************** */\r
475 \r
476 // WARNING: this function does not work in Flash Player 10\r
477 // Public: selectFile causes a File Selection Dialog window to appear.  This\r
478 // dialog only allows 1 file to be selected.\r
479 SWFUpload.prototype.selectFile = function () {\r
480         this.callFlash("SelectFile");\r
481 };\r
482 \r
483 // WARNING: this function does not work in Flash Player 10\r
484 // Public: selectFiles causes a File Selection Dialog window to appear/ This\r
485 // dialog allows the user to select any number of files\r
486 // Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.\r
487 // If the selection name length is too long the dialog will fail in an unpredictable manner.  There is no work-around\r
488 // for this bug.\r
489 SWFUpload.prototype.selectFiles = function () {\r
490         this.callFlash("SelectFiles");\r
491 };\r
492 \r
493 \r
494 // Public: startUpload starts uploading the first file in the queue unless\r
495 // the optional parameter 'fileID' specifies the ID \r
496 SWFUpload.prototype.startUpload = function (fileID) {\r
497         this.callFlash("StartUpload", [fileID]);\r
498 };\r
499 \r
500 // Public: cancelUpload cancels any queued file.  The fileID parameter may be the file ID or index.\r
501 // If you do not specify a fileID the current uploading file or first file in the queue is cancelled.\r
502 // If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter.\r
503 SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {\r
504         if (triggerErrorEvent !== false) {\r
505                 triggerErrorEvent = true;\r
506         }\r
507         this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);\r
508 };\r
509 \r
510 // Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.\r
511 // If nothing is currently uploading then nothing happens.\r
512 SWFUpload.prototype.stopUpload = function () {\r
513         this.callFlash("StopUpload");\r
514 };\r
515 \r
516 /* ************************\r
517  * Settings methods\r
518  *   These methods change the SWFUpload settings.\r
519  *   SWFUpload settings should not be changed directly on the settings object\r
520  *   since many of the settings need to be passed to Flash in order to take\r
521  *   effect.\r
522  * *********************** */\r
523 \r
524 // Public: getStats gets the file statistics object.\r
525 SWFUpload.prototype.getStats = function () {\r
526         return this.callFlash("GetStats");\r
527 };\r
528 \r
529 // Public: setStats changes the SWFUpload statistics.  You shouldn't need to \r
530 // change the statistics but you can.  Changing the statistics does not\r
531 // affect SWFUpload accept for the successful_uploads count which is used\r
532 // by the upload_limit setting to determine how many files the user may upload.\r
533 SWFUpload.prototype.setStats = function (statsObject) {\r
534         this.callFlash("SetStats", [statsObject]);\r
535 };\r
536 \r
537 // Public: getFile retrieves a File object by ID or Index.  If the file is\r
538 // not found then 'null' is returned.\r
539 SWFUpload.prototype.getFile = function (fileID) {\r
540         if (typeof(fileID) === "number") {\r
541                 return this.callFlash("GetFileByIndex", [fileID]);\r
542         } else {\r
543                 return this.callFlash("GetFile", [fileID]);\r
544         }\r
545 };\r
546 \r
547 // Public: addFileParam sets a name/value pair that will be posted with the\r
548 // file specified by the Files ID.  If the name already exists then the\r
549 // exiting value will be overwritten.\r
550 SWFUpload.prototype.addFileParam = function (fileID, name, value) {\r
551         return this.callFlash("AddFileParam", [fileID, name, value]);\r
552 };\r
553 \r
554 // Public: removeFileParam removes a previously set (by addFileParam) name/value\r
555 // pair from the specified file.\r
556 SWFUpload.prototype.removeFileParam = function (fileID, name) {\r
557         this.callFlash("RemoveFileParam", [fileID, name]);\r
558 };\r
559 \r
560 // Public: setUploadUrl changes the upload_url setting.\r
561 SWFUpload.prototype.setUploadURL = function (url) {\r
562         this.settings.upload_url = url.toString();\r
563         this.callFlash("SetUploadURL", [url]);\r
564 };\r
565 \r
566 // Public: setPostParams changes the post_params setting\r
567 SWFUpload.prototype.setPostParams = function (paramsObject) {\r
568         this.settings.post_params = paramsObject;\r
569         this.callFlash("SetPostParams", [paramsObject]);\r
570 };\r
571 \r
572 // Public: addPostParam adds post name/value pair.  Each name can have only one value.\r
573 SWFUpload.prototype.addPostParam = function (name, value) {\r
574         this.settings.post_params[name] = value;\r
575         this.callFlash("SetPostParams", [this.settings.post_params]);\r
576 };\r
577 \r
578 // Public: removePostParam deletes post name/value pair.\r
579 SWFUpload.prototype.removePostParam = function (name) {\r
580         delete this.settings.post_params[name];\r
581         this.callFlash("SetPostParams", [this.settings.post_params]);\r
582 };\r
583 \r
584 // Public: setFileTypes changes the file_types setting and the file_types_description setting\r
585 SWFUpload.prototype.setFileTypes = function (types, description) {\r
586         this.settings.file_types = types;\r
587         this.settings.file_types_description = description;\r
588         this.callFlash("SetFileTypes", [types, description]);\r
589 };\r
590 \r
591 // Public: setFileSizeLimit changes the file_size_limit setting\r
592 SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {\r
593         this.settings.file_size_limit = fileSizeLimit;\r
594         this.callFlash("SetFileSizeLimit", [fileSizeLimit]);\r
595 };\r
596 \r
597 // Public: setFileUploadLimit changes the file_upload_limit setting\r
598 SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {\r
599         this.settings.file_upload_limit = fileUploadLimit;\r
600         this.callFlash("SetFileUploadLimit", [fileUploadLimit]);\r
601 };\r
602 \r
603 // Public: setFileQueueLimit changes the file_queue_limit setting\r
604 SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {\r
605         this.settings.file_queue_limit = fileQueueLimit;\r
606         this.callFlash("SetFileQueueLimit", [fileQueueLimit]);\r
607 };\r
608 \r
609 // Public: setFilePostName changes the file_post_name setting\r
610 SWFUpload.prototype.setFilePostName = function (filePostName) {\r
611         this.settings.file_post_name = filePostName;\r
612         this.callFlash("SetFilePostName", [filePostName]);\r
613 };\r
614 \r
615 // Public: setUseQueryString changes the use_query_string setting\r
616 SWFUpload.prototype.setUseQueryString = function (useQueryString) {\r
617         this.settings.use_query_string = useQueryString;\r
618         this.callFlash("SetUseQueryString", [useQueryString]);\r
619 };\r
620 \r
621 // Public: setRequeueOnError changes the requeue_on_error setting\r
622 SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {\r
623         this.settings.requeue_on_error = requeueOnError;\r
624         this.callFlash("SetRequeueOnError", [requeueOnError]);\r
625 };\r
626 \r
627 // Public: setHTTPSuccess changes the http_success setting\r
628 SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {\r
629         if (typeof http_status_codes === "string") {\r
630                 http_status_codes = http_status_codes.replace(" ", "").split(",");\r
631         }\r
632         \r
633         this.settings.http_success = http_status_codes;\r
634         this.callFlash("SetHTTPSuccess", [http_status_codes]);\r
635 };\r
636 \r
637 // Public: setHTTPSuccess changes the http_success setting\r
638 SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) {\r
639         this.settings.assume_success_timeout = timeout_seconds;\r
640         this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]);\r
641 };\r
642 \r
643 // Public: setDebugEnabled changes the debug_enabled setting\r
644 SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {\r
645         this.settings.debug_enabled = debugEnabled;\r
646         this.callFlash("SetDebugEnabled", [debugEnabled]);\r
647 };\r
648 \r
649 // Public: setButtonImageURL loads a button image sprite\r
650 SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {\r
651         if (buttonImageURL == undefined) {\r
652                 buttonImageURL = "";\r
653         }\r
654         \r
655         this.settings.button_image_url = buttonImageURL;\r
656         this.callFlash("SetButtonImageURL", [buttonImageURL]);\r
657 };\r
658 \r
659 // Public: setButtonDimensions resizes the Flash Movie and button\r
660 SWFUpload.prototype.setButtonDimensions = function (width, height) {\r
661         this.settings.button_width = width;\r
662         this.settings.button_height = height;\r
663         \r
664         var movie = this.getMovieElement();\r
665         if (movie != undefined) {\r
666                 movie.style.width = width + "px";\r
667                 movie.style.height = height + "px";\r
668         }\r
669         \r
670         this.callFlash("SetButtonDimensions", [width, height]);\r
671 };\r
672 // Public: setButtonText Changes the text overlaid on the button\r
673 SWFUpload.prototype.setButtonText = function (html) {\r
674         this.settings.button_text = html;\r
675         this.callFlash("SetButtonText", [html]);\r
676 };\r
677 // Public: setButtonTextPadding changes the top and left padding of the text overlay\r
678 SWFUpload.prototype.setButtonTextPadding = function (left, top) {\r
679         this.settings.button_text_top_padding = top;\r
680         this.settings.button_text_left_padding = left;\r
681         this.callFlash("SetButtonTextPadding", [left, top]);\r
682 };\r
683 \r
684 // Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button\r
685 SWFUpload.prototype.setButtonTextStyle = function (css) {\r
686         this.settings.button_text_style = css;\r
687         this.callFlash("SetButtonTextStyle", [css]);\r
688 };\r
689 // Public: setButtonDisabled disables/enables the button\r
690 SWFUpload.prototype.setButtonDisabled = function (isDisabled) {\r
691         this.settings.button_disabled = isDisabled;\r
692         this.callFlash("SetButtonDisabled", [isDisabled]);\r
693 };\r
694 // Public: setButtonAction sets the action that occurs when the button is clicked\r
695 SWFUpload.prototype.setButtonAction = function (buttonAction) {\r
696         this.settings.button_action = buttonAction;\r
697         this.callFlash("SetButtonAction", [buttonAction]);\r
698 };\r
699 \r
700 // Public: setButtonCursor changes the mouse cursor displayed when hovering over the button\r
701 SWFUpload.prototype.setButtonCursor = function (cursor) {\r
702         this.settings.button_cursor = cursor;\r
703         this.callFlash("SetButtonCursor", [cursor]);\r
704 };\r
705 \r
706 /* *******************************\r
707         Flash Event Interfaces\r
708         These functions are used by Flash to trigger the various\r
709         events.\r
710         \r
711         All these functions a Private.\r
712         \r
713         Because the ExternalInterface library is buggy the event calls\r
714         are added to a queue and the queue then executed by a setTimeout.\r
715         This ensures that events are executed in a determinate order and that\r
716         the ExternalInterface bugs are avoided.\r
717 ******************************* */\r
718 \r
719 SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {\r
720         // Warning: Don't call this.debug inside here or you'll create an infinite loop\r
721         \r
722         if (argumentArray == undefined) {\r
723                 argumentArray = [];\r
724         } else if (!(argumentArray instanceof Array)) {\r
725                 argumentArray = [argumentArray];\r
726         }\r
727         \r
728         var self = this;\r
729         if (typeof this.settings[handlerName] === "function") {\r
730                 // Queue the event\r
731                 this.eventQueue.push(function () {\r
732                         this.settings[handlerName].apply(this, argumentArray);\r
733                 });\r
734                 \r
735                 // Execute the next queued event\r
736                 setTimeout(function () {\r
737                         self.executeNextEvent();\r
738                 }, 0);\r
739                 \r
740         } else if (this.settings[handlerName] !== null) {\r
741                 throw "Event handler " + handlerName + " is unknown or is not a function";\r
742         }\r
743 };\r
744 \r
745 // Private: Causes the next event in the queue to be executed.  Since events are queued using a setTimeout\r
746 // we must queue them in order to garentee that they are executed in order.\r
747 SWFUpload.prototype.executeNextEvent = function () {\r
748         // Warning: Don't call this.debug inside here or you'll create an infinite loop\r
749 \r
750         var  f = this.eventQueue ? this.eventQueue.shift() : null;\r
751         if (typeof(f) === "function") {\r
752                 f.apply(this);\r
753         }\r
754 };\r
755 \r
756 // Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have\r
757 // properties that contain characters that are not valid for JavaScript identifiers. To work around this\r
758 // the Flash Component escapes the parameter names and we must unescape again before passing them along.\r
759 SWFUpload.prototype.unescapeFilePostParams = function (file) {\r
760         var reg = /[$]([0-9a-f]{4})/i;\r
761         var unescapedPost = {};\r
762         var uk;\r
763 \r
764         if (file != undefined) {\r
765                 for (var k in file.post) {\r
766                         if (file.post.hasOwnProperty(k)) {\r
767                                 uk = k;\r
768                                 var match;\r
769                                 while ((match = reg.exec(uk)) !== null) {\r
770                                         uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));\r
771                                 }\r
772                                 unescapedPost[uk] = file.post[k];\r
773                         }\r
774                 }\r
775 \r
776                 file.post = unescapedPost;\r
777         }\r
778 \r
779         return file;\r
780 };\r
781 \r
782 // Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working)\r
783 SWFUpload.prototype.testExternalInterface = function () {\r
784         try {\r
785                 return this.callFlash("TestExternalInterface");\r
786         } catch (ex) {\r
787                 return false;\r
788         }\r
789 };\r
790 \r
791 // Private: This event is called by Flash when it has finished loading. Don't modify this.\r
792 // Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded.\r
793 SWFUpload.prototype.flashReady = function () {\r
794         // Check that the movie element is loaded correctly with its ExternalInterface methods defined\r
795         var movieElement = this.getMovieElement();\r
796 \r
797         if (!movieElement) {\r
798                 this.debug("Flash called back ready but the flash movie can't be found.");\r
799                 return;\r
800         }\r
801 \r
802         this.cleanUp(movieElement);\r
803         \r
804         this.queueEvent("swfupload_loaded_handler");\r
805 };\r
806 \r
807 // Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE.\r
808 // This function is called by Flash each time the ExternalInterface functions are created.\r
809 SWFUpload.prototype.cleanUp = function (movieElement) {\r
810         // Pro-actively unhook all the Flash functions\r
811         try {\r
812                 if (this.movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE\r
813                         this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");\r
814                         for (var key in movieElement) {\r
815                                 try {\r
816                                         if (typeof(movieElement[key]) === "function") {\r
817                                                 movieElement[key] = null;\r
818                                         }\r
819                                 } catch (ex) {\r
820                                 }\r
821                         }\r
822                 }\r
823         } catch (ex1) {\r
824         \r
825         }\r
826 \r
827         // Fix Flashes own cleanup code so if the SWFMovie was removed from the page\r
828         // it doesn't display errors.\r
829         window["__flash__removeCallback"] = function (instance, name) {\r
830                 try {\r
831                         if (instance) {\r
832                                 instance[name] = null;\r
833                         }\r
834                 } catch (flashEx) {\r
835                 \r
836                 }\r
837         };\r
838 \r
839 };\r
840 \r
841 \r
842 /* This is a chance to do something before the browse window opens */\r
843 SWFUpload.prototype.fileDialogStart = function () {\r
844         this.queueEvent("file_dialog_start_handler");\r
845 };\r
846 \r
847 \r
848 /* Called when a file is successfully added to the queue. */\r
849 SWFUpload.prototype.fileQueued = function (file) {\r
850         file = this.unescapeFilePostParams(file);\r
851         this.queueEvent("file_queued_handler", file);\r
852 };\r
853 \r
854 \r
855 /* Handle errors that occur when an attempt to queue a file fails. */\r
856 SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {\r
857         file = this.unescapeFilePostParams(file);\r
858         this.queueEvent("file_queue_error_handler", [file, errorCode, message]);\r
859 };\r
860 \r
861 /* Called after the file dialog has closed and the selected files have been queued.\r
862         You could call startUpload here if you want the queued files to begin uploading immediately. */\r
863 SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) {\r
864         this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]);\r
865 };\r
866 \r
867 SWFUpload.prototype.uploadStart = function (file) {\r
868         file = this.unescapeFilePostParams(file);\r
869         this.queueEvent("return_upload_start_handler", file);\r
870 };\r
871 \r
872 SWFUpload.prototype.returnUploadStart = function (file) {\r
873         var returnValue;\r
874         if (typeof this.settings.upload_start_handler === "function") {\r
875                 file = this.unescapeFilePostParams(file);\r
876                 returnValue = this.settings.upload_start_handler.call(this, file);\r
877         } else if (this.settings.upload_start_handler != undefined) {\r
878                 throw "upload_start_handler must be a function";\r
879         }\r
880 \r
881         // Convert undefined to true so if nothing is returned from the upload_start_handler it is\r
882         // interpretted as 'true'.\r
883         if (returnValue === undefined) {\r
884                 returnValue = true;\r
885         }\r
886         \r
887         returnValue = !!returnValue;\r
888         \r
889         this.callFlash("ReturnUploadStart", [returnValue]);\r
890 };\r
891 \r
892 \r
893 \r
894 SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {\r
895         file = this.unescapeFilePostParams(file);\r
896         this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);\r
897 };\r
898 \r
899 SWFUpload.prototype.uploadError = function (file, errorCode, message) {\r
900         file = this.unescapeFilePostParams(file);\r
901         this.queueEvent("upload_error_handler", [file, errorCode, message]);\r
902 };\r
903 \r
904 SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) {\r
905         file = this.unescapeFilePostParams(file);\r
906         this.queueEvent("upload_success_handler", [file, serverData, responseReceived]);\r
907 };\r
908 \r
909 SWFUpload.prototype.uploadComplete = function (file) {\r
910         file = this.unescapeFilePostParams(file);\r
911         this.queueEvent("upload_complete_handler", file);\r
912 };\r
913 \r
914 /* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the\r
915    internal debug console.  You can override this event and have messages written where you want. */\r
916 SWFUpload.prototype.debug = function (message) {\r
917         this.queueEvent("debug_handler", message);\r
918 };\r
919 \r
920 \r
921 /* **********************************\r
922         Debug Console\r
923         The debug console is a self contained, in page location\r
924         for debug message to be sent.  The Debug Console adds\r
925         itself to the body if necessary.\r
926 \r
927         The console is automatically scrolled as messages appear.\r
928         \r
929         If you are using your own debug handler or when you deploy to production and\r
930         have debug disabled you can remove these functions to reduce the file size\r
931         and complexity.\r
932 ********************************** */\r
933    \r
934 // Private: debugMessage is the default debug_handler.  If you want to print debug messages\r
935 // call the debug() function.  When overriding the function your own function should\r
936 // check to see if the debug setting is true before outputting debug information.\r
937 SWFUpload.prototype.debugMessage = function (message) {\r
938         if (this.settings.debug) {\r
939                 var exceptionMessage, exceptionValues = [];\r
940 \r
941                 // Check for an exception object and print it nicely\r
942                 if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {\r
943                         for (var key in message) {\r
944                                 if (message.hasOwnProperty(key)) {\r
945                                         exceptionValues.push(key + ": " + message[key]);\r
946                                 }\r
947                         }\r
948                         exceptionMessage = exceptionValues.join("\n") || "";\r
949                         exceptionValues = exceptionMessage.split("\n");\r
950                         exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");\r
951                         SWFUpload.Console.writeLine(exceptionMessage);\r
952                 } else {\r
953                         SWFUpload.Console.writeLine(message);\r
954                 }\r
955         }\r
956 };\r
957 \r
958 SWFUpload.Console = {};\r
959 SWFUpload.Console.writeLine = function (message) {\r
960         var console, documentForm;\r
961 \r
962         try {\r
963                 console = document.getElementById("SWFUpload_Console");\r
964 \r
965                 if (!console) {\r
966                         documentForm = document.createElement("form");\r
967                         document.getElementsByTagName("body")[0].appendChild(documentForm);\r
968 \r
969                         console = document.createElement("textarea");\r
970                         console.id = "SWFUpload_Console";\r
971                         console.style.fontFamily = "monospace";\r
972                         console.setAttribute("wrap", "off");\r
973                         console.wrap = "off";\r
974                         console.style.overflow = "auto";\r
975                         console.style.width = "700px";\r
976                         console.style.height = "350px";\r
977                         console.style.margin = "5px";\r
978                         documentForm.appendChild(console);\r
979                 }\r
980 \r
981                 console.value += message + "\n";\r
982 \r
983                 console.scrollTop = console.scrollHeight - console.clientHeight;\r
984         } catch (ex) {\r
985                 alert("Exception: " + ex.name + " Message: " + ex.message);\r
986         }\r
987 };\r
988 </pre>    \r
989 </body>\r
990 </html>