2 * AJAX Upload ( http://valums.com/ajax-upload/ )
3 * Copyright (c) Andris Valums
4 * Licensed under the MIT license ( http://valums.com/mit-license/ )
5 * Thanks to Gary Haran, David Mark, Corey Burns and others for contributions.
10 /* jslint browser: true, devel: true, undef: true, nomen: true, bitwise: true, regexp: true, newcap: true, immed: true */
13 * Wrapper for FireBug's console.log
16 if (typeof(console) != 'undefined' && typeof(console.log) == 'function'){
17 Array.prototype.unshift.call(arguments, '[Ajax Upload]');
18 console.log( Array.prototype.join.call(arguments, ' '));
23 * Attaches event to a dom element.
25 * @param type event name
26 * @param fn callback This refers to the passed element
28 function addEvent(el, type, fn){
29 if (el.addEventListener) {
30 el.addEventListener(type, fn, false);
31 } else if (el.attachEvent) {
32 el.attachEvent('on' + type, function(){
36 throw new Error('not supported or DOM not loaded');
41 * Attaches resize event to a window, limiting
42 * number of event fired. Fires only when encounteres
43 * delay of 100 after series of events.
45 * Some browsers fire event multiple times when resizing
46 * http://www.quirksmode.org/dom/events/resize.html
48 * @param fn callback This refers to the passed element
50 function addResizeEvent(fn){
53 addEvent(window, 'resize', function(){
55 clearTimeout(timeout);
57 timeout = setTimeout(fn, 100);
61 // Needs more testing, will be rewriten for next version
62 // getOffset function copied from jQuery lib (http://jquery.com/)
63 if (document.documentElement.getBoundingClientRect){
64 // Get Offset using getBoundingClientRect
65 // http://ejohn.org/blog/getboundingclientrect-is-awesome/
66 var getOffset = function(el){
67 var box = el.getBoundingClientRect();
68 var doc = el.ownerDocument;
70 var docElem = doc.documentElement; // for ie
71 var clientTop = docElem.clientTop || body.clientTop || 0;
72 var clientLeft = docElem.clientLeft || body.clientLeft || 0;
74 // In Internet Explorer 7 getBoundingClientRect property is treated as physical,
75 // while others are logical. Make all logical, like in IE8.
77 if (body.getBoundingClientRect) {
78 var bound = body.getBoundingClientRect();
79 zoom = (bound.right - bound.left) / body.clientWidth;
87 var top = box.top / zoom + (window.pageYOffset || docElem && docElem.scrollTop / zoom || body.scrollTop / zoom) - clientTop, left = box.left / zoom + (window.pageXOffset || docElem && docElem.scrollLeft / zoom || body.scrollLeft / zoom) - clientLeft;
95 // Get offset adding all offsets
96 var getOffset = function(el){
97 var top = 0, left = 0;
99 top += el.offsetTop || 0;
100 left += el.offsetLeft || 0;
101 el = el.offsetParent;
112 * Returns left, top, right and bottom properties describing the border-box,
113 * in pixels, with the top-left relative to the body
114 * @param {Element} el
115 * @return {Object} Contains left, top, right,bottom
118 var left, right, top, bottom;
119 var offset = getOffset(el);
123 right = left + el.offsetWidth;
124 bottom = top + el.offsetHeight;
135 * Helper that takes object literal
136 * and add all properties to element.style
137 * @param {Element} el
138 * @param {Object} styles
140 function addStyles(el, styles){
141 for (var name in styles) {
142 if (styles.hasOwnProperty(name)) {
143 el.style[name] = styles[name];
149 * Function places an absolutely positioned
150 * element on top of the specified element
151 * copying position and dimentions.
152 * @param {Element} from
153 * @param {Element} to
155 function copyLayout(from, to){
156 var box = getBox(from);
159 position: 'absolute',
160 left : box.left + 'px',
161 top : box.top + 'px',
162 width : from.offsetWidth + 'px',
163 height : from.offsetHeight + 'px'
165 to.title = from.title;
170 * Creates and returns element from html chunk
171 * Uses innerHTML to create an element
173 var toElement = (function(){
174 var div = document.createElement('div');
175 return function(html){
176 div.innerHTML = html;
177 var el = div.firstChild;
178 return div.removeChild(el);
183 * Function generates unique id
186 var getUID = (function(){
189 return 'ValumsAjaxUpload' + id++;
194 * Get file name from path
195 * @param {String} file path to file
198 function fileFromPath(file){
199 return file.replace(/.*(\/|\\)/, "");
203 * Get file extension lowercase
204 * @param {String} file name
205 * @return file extenstion
207 function getExt(file){
208 return (-1 !== file.indexOf('.')) ? file.replace(/.*[.]/, '') : '';
211 function hasClass(el, name){
212 var re = new RegExp('\\b' + name + '\\b');
213 return re.test(el.className);
215 function addClass(el, name){
216 if ( ! hasClass(el, name)){
217 el.className += ' ' + name;
220 function removeClass(el, name){
221 var re = new RegExp('\\b' + name + '\\b');
222 el.className = el.className.replace(re, '');
225 function removeNode(el){
226 el.parentNode.removeChild(el);
230 * Easy styling and uploading
232 * @param button An element you want convert to
233 * upload button. Tested dimentions up to 500x500px
234 * @param {Object} options See defaults below.
236 window.AjaxUpload = function(button, options){
238 // Location of the server-side upload script
239 action: 'upload.php',
242 // Additional data to send
244 // Submit file as soon as it's selected
246 // The type of data that you're expecting back from the server.
247 // html and xml are detected automatically.
248 // Only useful when you are using json data as a response.
249 // Set to "json" in that case.
251 // Class applied to button when mouse is hovered
253 // Class applied to button when button is focused
255 // Class applied to button when AU is disabled
256 disabledClass: 'disabled',
257 // When user selects a file, useful with autoSubmit disabled
258 // You can return false to cancel upload
259 onChange: function(file, extension){
261 // Callback to fire before file is uploaded
262 // You can return false to cancel upload
263 onSubmit: function(file, extension){
265 // Fired when file upload is completed
266 // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
267 onComplete: function(file, response){
271 // Merge the users options with our defaults
272 for (var i in options) {
273 if (options.hasOwnProperty(i)){
274 this._settings[i] = options[i];
278 // button isn't necessary a dom element
280 // jQuery object was passed
282 } else if (typeof button == "string") {
283 if (/^#.*/.test(button)){
284 // If jQuery user passes #elementId don't break it
285 button = button.slice(1);
288 button = document.getElementById(button);
291 if ( ! button || button.nodeType !== 1){
292 throw new Error("Please make sure that you're passing a valid element");
295 if ( button.nodeName.toUpperCase() == 'A'){
297 addEvent(button, 'click', function(e){
298 if (e && e.preventDefault){
300 } else if (window.event){
301 window.event.returnValue = false;
307 this._button = button;
310 // If disabled clicking on button won't do anything
311 this._disabled = false;
313 // if the button was disabled before refresh if will remain
314 // disabled in FireFox, let's fix it
317 this._rerouteClicks();
320 // assigning methods to our class
321 AjaxUpload.prototype = {
322 setData: function(data){
323 this._settings.data = data;
326 addClass(this._button, this._settings.disabledClass);
327 this._disabled = true;
329 var nodeName = this._button.nodeName.toUpperCase();
330 if (nodeName == 'INPUT' || nodeName == 'BUTTON'){
331 this._button.setAttribute('disabled', 'disabled');
336 // We use visibility instead of display to fix problem with Safari 4
337 // The problem is that the value of input doesn't change if it
338 // has display none when user selects a file
339 this._input.parentNode.style.visibility = 'hidden';
343 removeClass(this._button, this._settings.disabledClass);
344 this._button.removeAttribute('disabled');
345 this._disabled = false;
349 * Creates invisible file input
350 * that will hover above the button
351 * <div><input type='file' /></div>
353 _createInput: function(){
356 var input = document.createElement("input");
357 input.setAttribute('type', 'file');
358 input.setAttribute('name', this._settings.name);
361 'position' : 'absolute',
362 // in Opera only 'browse' button
363 // is clickable and it is located at
364 // the right side of the input
368 'fontSize' : '480px',
369 // in Firefox if font-family is set to
370 // 'inherit' the input doesn't work
371 'fontFamily' : 'sans-serif',
375 var div = document.createElement("div");
378 'position' : 'absolute',
379 'overflow' : 'hidden',
383 // Make sure browse button is in the right side
384 // in Internet Explorer
386 //Max zIndex supported by Opera 9.0-9.2
387 'zIndex': 2147483583,
392 // Make sure that element opacity exists.
393 // Otherwise use IE filter
394 if ( div.style.opacity !== "0") {
395 if (typeof(div.filters) == 'undefined'){
396 throw new Error('Opacity not supported by the browser');
398 div.style.filter = "alpha(opacity=0)";
401 addEvent(input, 'change', function(){
403 if ( ! input || input.value === ''){
407 // Get filename from input, required
408 // as some browsers have path instead of it
409 var file = fileFromPath(input.value);
411 if (false === self._settings.onChange.call(self, file, getExt(file))){
416 // Submit form when value is changed
417 if (self._settings.autoSubmit) {
422 addEvent(input, 'mouseover', function(){
423 addClass(self._button, self._settings.hoverClass);
426 addEvent(input, 'mouseout', function(){
427 removeClass(self._button, self._settings.hoverClass);
428 removeClass(self._button, self._settings.focusClass);
430 // We use visibility instead of display to fix problem with Safari 4
431 // The problem is that the value of input doesn't change if it
432 // has display none when user selects a file
433 input.parentNode.style.visibility = 'hidden';
437 addEvent(input, 'focus', function(){
438 addClass(self._button, self._settings.focusClass);
441 addEvent(input, 'blur', function(){
442 removeClass(self._button, self._settings.focusClass);
445 div.appendChild(input);
446 document.body.appendChild(div);
450 _clearInput : function(){
455 // this._input.value = ''; Doesn't work in IE6
456 removeNode(this._input.parentNode);
460 removeClass(this._button, this._settings.hoverClass);
461 removeClass(this._button, this._settings.focusClass);
464 * Function makes sure that when user clicks upload button,
465 * the this._input is clicked instead
467 _rerouteClicks: function(){
470 // IE will later display 'access denied' error
471 // if you use using self._input.click()
472 // other browsers just ignore click()
474 addEvent(self._button, 'mouseover', function(){
483 var div = self._input.parentNode;
484 copyLayout(self._button, div);
485 div.style.visibility = 'visible';
490 // commented because we now hide input on mouseleave
492 * When the window is resized the elements
493 * can be misaligned if button position depends
496 //addResizeEvent(function(){
498 // copyLayout(self._button, self._input.parentNode);
504 * Creates iframe with unique name
505 * @return {Element} iframe
507 _createIframe: function(){
508 // We can't use getTime, because it sometimes return
509 // same value in safari :(
512 // We can't use following code as the name attribute
513 // won't be properly registered in IE6, and new window
514 // on form submit will open
515 // var iframe = document.createElement('iframe');
516 // iframe.setAttribute('name', id);
518 var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
519 // src="javascript:false; was added
520 // because it possibly removes ie6 prompt
521 // "This page contains both secure and nonsecure items"
522 // Anyway, it doesn't do any harm.
523 iframe.setAttribute('id', id);
525 iframe.style.display = 'none';
526 document.body.appendChild(iframe);
531 * Creates form, that will be submitted to iframe
532 * @param {Element} iframe Where to submit
533 * @return {Element} form
535 _createForm: function(iframe){
536 var settings = this._settings;
538 // We can't use the following code in IE6
539 // var form = document.createElement('form');
540 // form.setAttribute('method', 'post');
541 // form.setAttribute('enctype', 'multipart/form-data');
542 // Because in this case file won't be attached to request
543 var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
545 form.setAttribute('action', settings.action);
546 form.setAttribute('target', iframe.name);
547 form.style.display = 'none';
548 document.body.appendChild(form);
550 // Create hidden input element for each data key
551 for (var prop in settings.data) {
552 if (settings.data.hasOwnProperty(prop)){
553 var el = document.createElement("input");
554 el.setAttribute('type', 'hidden');
555 el.setAttribute('name', prop);
556 el.setAttribute('value', settings.data[prop]);
557 form.appendChild(el);
563 * Gets response from iframe and fires onComplete event when ready
565 * @param file Filename to use in onComplete callback
567 _getResponse : function(iframe, file){
569 var toDeleteFlag = false, self = this, settings = this._settings;
571 addEvent(iframe, 'load', function(){
574 iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
576 iframe.src == "javascript:'<html></html>';"){
577 // First time around, do not delete.
578 // We reload to blank page, so that reloading main page
579 // does not re-submit the post.
582 // Fix busy state in FF3
583 setTimeout(function(){
591 var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document;
593 // fixing Opera 9.26,10.00
594 if (doc.readyState && doc.readyState != 'complete') {
595 // Opera fires load event multiple times
596 // Even when the DOM is not ready yet
597 // this fix should not affect other browsers
602 if (doc.body && doc.body.innerHTML == "false") {
603 // In Opera 9.64 event was fired second time
604 // when body.innerHTML changed from false
605 // to server response approx. after 1 sec
611 if (doc.XMLDocument) {
612 // response is a xml document Internet Explorer property
613 response = doc.XMLDocument;
614 } else if (doc.body){
615 // response is html document or plain text
616 response = doc.body.innerHTML;
618 if (settings.responseType && settings.responseType.toLowerCase() == 'json') {
619 // If the document was sent as 'application/javascript' or
620 // 'text/javascript', then the browser wraps the text in a <pre>
621 // tag and performs html encoding on the contents. In this case,
622 // we need to pull the original text content from the text node's
623 // nodeValue property to retrieve the unmangled content.
624 // Note that IE6 only understands text/html
625 if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') {
627 response = doc.body.firstChild.firstChild.nodeValue;
631 response = eval("(" + response + ")");
637 // response is a xml document
641 settings.onComplete.call(self, file, response);
643 // Reload blank page, so that reloading main page
644 // does not re-submit the post. Also, remember to
648 // Fix IE mixed content issue
649 iframe.src = "javascript:'<html></html>';";
653 * Upload file contained in this._input
656 var self = this, settings = this._settings;
658 if ( ! this._input || this._input.value === ''){
662 var file = fileFromPath(this._input.value);
664 // user returned false to cancel upload
665 if (false === settings.onSubmit.call(this, file, getExt(file))){
671 var iframe = this._createIframe();
672 var form = this._createForm(iframe);
674 // assuming following structure
675 // div -> input type='file'
676 removeNode(this._input.parentNode);
677 removeClass(self._button, self._settings.hoverClass);
678 removeClass(self._button, self._settings.focusClass);
680 form.appendChild(this._input);
684 // request set, clean up
685 removeNode(form); form = null;
686 removeNode(this._input); this._input = null;
688 // Get response from iframe and fire onComplete event when ready
689 this._getResponse(iframe, file);
691 // get ready for next request