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;
169 * Creates and returns element from html chunk
170 * Uses innerHTML to create an element
172 var toElement = (function(){
173 var div = document.createElement('div');
174 return function(html){
175 div.innerHTML = html;
176 var el = div.firstChild;
177 return div.removeChild(el);
182 * Function generates unique id
185 var getUID = (function(){
188 return 'ValumsAjaxUpload' + id++;
193 * Get file name from path
194 * @param {String} file path to file
197 function fileFromPath(file){
198 return file.replace(/.*(\/|\\)/, "");
202 * Get file extension lowercase
203 * @param {String} file name
204 * @return file extenstion
206 function getExt(file){
207 return (-1 !== file.indexOf('.')) ? file.replace(/.*[.]/, '') : '';
210 function hasClass(el, name){
211 var re = new RegExp('\\b' + name + '\\b');
212 return re.test(el.className);
214 function addClass(el, name){
215 if ( ! hasClass(el, name)){
216 el.className += ' ' + name;
219 function removeClass(el, name){
220 var re = new RegExp('\\b' + name + '\\b');
221 el.className = el.className.replace(re, '');
224 function removeNode(el){
225 el.parentNode.removeChild(el);
229 * Easy styling and uploading
231 * @param button An element you want convert to
232 * upload button. Tested dimentions up to 500x500px
233 * @param {Object} options See defaults below.
235 window.AjaxUpload = function(button, options){
237 // Location of the server-side upload script
238 action: 'upload.php',
241 // Additional data to send
243 // Submit file as soon as it's selected
245 // The type of data that you're expecting back from the server.
246 // html and xml are detected automatically.
247 // Only useful when you are using json data as a response.
248 // Set to "json" in that case.
250 // Class applied to button when mouse is hovered
252 // Class applied to button when button is focused
254 // Class applied to button when AU is disabled
255 disabledClass: 'disabled',
256 // When user selects a file, useful with autoSubmit disabled
257 // You can return false to cancel upload
258 onChange: function(file, extension){
260 // Callback to fire before file is uploaded
261 // You can return false to cancel upload
262 onSubmit: function(file, extension){
264 // Fired when file upload is completed
265 // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
266 onComplete: function(file, response){
270 // Merge the users options with our defaults
271 for (var i in options) {
272 if (options.hasOwnProperty(i)){
273 this._settings[i] = options[i];
277 // button isn't necessary a dom element
279 // jQuery object was passed
281 } else if (typeof button == "string") {
282 if (/^#.*/.test(button)){
283 // If jQuery user passes #elementId don't break it
284 button = button.slice(1);
287 button = document.getElementById(button);
290 if ( ! button || button.nodeType !== 1){
291 throw new Error("Please make sure that you're passing a valid element");
294 if ( button.nodeName.toUpperCase() == 'A'){
296 addEvent(button, 'click', function(e){
297 if (e && e.preventDefault){
299 } else if (window.event){
300 window.event.returnValue = false;
306 this._button = button;
309 // If disabled clicking on button won't do anything
310 this._disabled = false;
312 // if the button was disabled before refresh if will remain
313 // disabled in FireFox, let's fix it
316 this._rerouteClicks();
319 // assigning methods to our class
320 AjaxUpload.prototype = {
321 setData: function(data){
322 this._settings.data = data;
325 addClass(this._button, this._settings.disabledClass);
326 this._disabled = true;
328 var nodeName = this._button.nodeName.toUpperCase();
329 if (nodeName == 'INPUT' || nodeName == 'BUTTON'){
330 this._button.setAttribute('disabled', 'disabled');
335 // We use visibility instead of display to fix problem with Safari 4
336 // The problem is that the value of input doesn't change if it
337 // has display none when user selects a file
338 this._input.parentNode.style.visibility = 'hidden';
342 removeClass(this._button, this._settings.disabledClass);
343 this._button.removeAttribute('disabled');
344 this._disabled = false;
348 * Creates invisible file input
349 * that will hover above the button
350 * <div><input type='file' /></div>
352 _createInput: function(){
355 var input = document.createElement("input");
356 input.setAttribute('type', 'file');
357 input.setAttribute('name', this._settings.name);
360 'position' : 'absolute',
361 // in Opera only 'browse' button
362 // is clickable and it is located at
363 // the right side of the input
367 'fontSize' : '480px',
368 // in Firefox if font-family is set to
369 // 'inherit' the input doesn't work
370 'fontFamily' : 'sans-serif',
374 var div = document.createElement("div");
377 'position' : 'absolute',
378 'overflow' : 'hidden',
382 // Make sure browse button is in the right side
383 // in Internet Explorer
385 //Max zIndex supported by Opera 9.0-9.2
389 // Make sure that element opacity exists.
390 // Otherwise use IE filter
391 if ( div.style.opacity !== "0") {
392 if (typeof(div.filters) == 'undefined'){
393 throw new Error('Opacity not supported by the browser');
395 div.style.filter = "alpha(opacity=0)";
398 addEvent(input, 'change', function(){
400 if ( ! input || input.value === ''){
404 // Get filename from input, required
405 // as some browsers have path instead of it
406 var file = fileFromPath(input.value);
408 if (false === self._settings.onChange.call(self, file, getExt(file))){
413 // Submit form when value is changed
414 if (self._settings.autoSubmit) {
419 addEvent(input, 'mouseover', function(){
420 addClass(self._button, self._settings.hoverClass);
423 addEvent(input, 'mouseout', function(){
424 removeClass(self._button, self._settings.hoverClass);
425 removeClass(self._button, self._settings.focusClass);
427 // We use visibility instead of display to fix problem with Safari 4
428 // The problem is that the value of input doesn't change if it
429 // has display none when user selects a file
430 input.parentNode.style.visibility = 'hidden';
434 addEvent(input, 'focus', function(){
435 addClass(self._button, self._settings.focusClass);
438 addEvent(input, 'blur', function(){
439 removeClass(self._button, self._settings.focusClass);
442 div.appendChild(input);
443 document.body.appendChild(div);
447 _clearInput : function(){
452 // this._input.value = ''; Doesn't work in IE6
453 removeNode(this._input.parentNode);
457 removeClass(this._button, this._settings.hoverClass);
458 removeClass(this._button, this._settings.focusClass);
461 * Function makes sure that when user clicks upload button,
462 * the this._input is clicked instead
464 _rerouteClicks: function(){
467 // IE will later display 'access denied' error
468 // if you use using self._input.click()
469 // other browsers just ignore click()
471 addEvent(self._button, 'mouseover', function(){
480 var div = self._input.parentNode;
481 copyLayout(self._button, div);
482 div.style.visibility = 'visible';
487 // commented because we now hide input on mouseleave
489 * When the window is resized the elements
490 * can be misaligned if button position depends
493 //addResizeEvent(function(){
495 // copyLayout(self._button, self._input.parentNode);
501 * Creates iframe with unique name
502 * @return {Element} iframe
504 _createIframe: function(){
505 // We can't use getTime, because it sometimes return
506 // same value in safari :(
509 // We can't use following code as the name attribute
510 // won't be properly registered in IE6, and new window
511 // on form submit will open
512 // var iframe = document.createElement('iframe');
513 // iframe.setAttribute('name', id);
515 var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
516 // src="javascript:false; was added
517 // because it possibly removes ie6 prompt
518 // "This page contains both secure and nonsecure items"
519 // Anyway, it doesn't do any harm.
520 iframe.setAttribute('id', id);
522 iframe.style.display = 'none';
523 document.body.appendChild(iframe);
528 * Creates form, that will be submitted to iframe
529 * @param {Element} iframe Where to submit
530 * @return {Element} form
532 _createForm: function(iframe){
533 var settings = this._settings;
535 // We can't use the following code in IE6
536 // var form = document.createElement('form');
537 // form.setAttribute('method', 'post');
538 // form.setAttribute('enctype', 'multipart/form-data');
539 // Because in this case file won't be attached to request
540 var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
542 form.setAttribute('action', settings.action);
543 form.setAttribute('target', iframe.name);
544 form.style.display = 'none';
545 document.body.appendChild(form);
547 // Create hidden input element for each data key
548 for (var prop in settings.data) {
549 if (settings.data.hasOwnProperty(prop)){
550 var el = document.createElement("input");
551 el.setAttribute('type', 'hidden');
552 el.setAttribute('name', prop);
553 el.setAttribute('value', settings.data[prop]);
554 form.appendChild(el);
560 * Gets response from iframe and fires onComplete event when ready
562 * @param file Filename to use in onComplete callback
564 _getResponse : function(iframe, file){
566 var toDeleteFlag = false, self = this, settings = this._settings;
568 addEvent(iframe, 'load', function(){
571 iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
573 iframe.src == "javascript:'<html></html>';"){
574 // First time around, do not delete.
575 // We reload to blank page, so that reloading main page
576 // does not re-submit the post.
579 // Fix busy state in FF3
580 setTimeout(function(){
588 var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document;
590 // fixing Opera 9.26,10.00
591 if (doc.readyState && doc.readyState != 'complete') {
592 // Opera fires load event multiple times
593 // Even when the DOM is not ready yet
594 // this fix should not affect other browsers
599 if (doc.body && doc.body.innerHTML == "false") {
600 // In Opera 9.64 event was fired second time
601 // when body.innerHTML changed from false
602 // to server response approx. after 1 sec
608 if (doc.XMLDocument) {
609 // response is a xml document Internet Explorer property
610 response = doc.XMLDocument;
611 } else if (doc.body){
612 // response is html document or plain text
613 response = doc.body.innerHTML;
615 if (settings.responseType && settings.responseType.toLowerCase() == 'json') {
616 // If the document was sent as 'application/javascript' or
617 // 'text/javascript', then the browser wraps the text in a <pre>
618 // tag and performs html encoding on the contents. In this case,
619 // we need to pull the original text content from the text node's
620 // nodeValue property to retrieve the unmangled content.
621 // Note that IE6 only understands text/html
622 if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') {
624 response = doc.body.firstChild.firstChild.nodeValue;
628 response = eval("(" + response + ")");
634 // response is a xml document
638 settings.onComplete.call(self, file, response);
640 // Reload blank page, so that reloading main page
641 // does not re-submit the post. Also, remember to
645 // Fix IE mixed content issue
646 iframe.src = "javascript:'<html></html>';";
650 * Upload file contained in this._input
653 var self = this, settings = this._settings;
655 if ( ! this._input || this._input.value === ''){
659 var file = fileFromPath(this._input.value);
661 // user returned false to cancel upload
662 if (false === settings.onSubmit.call(this, file, getExt(file))){
668 var iframe = this._createIframe();
669 var form = this._createForm(iframe);
671 // assuming following structure
672 // div -> input type='file'
673 removeNode(this._input.parentNode);
674 removeClass(self._button, self._settings.hoverClass);
675 removeClass(self._button, self._settings.focusClass);
677 form.appendChild(this._input);
681 // request set, clean up
682 removeNode(form); form = null;
683 removeNode(this._input); this._input = null;
685 // Get response from iframe and fire onComplete event when ready
686 this._getResponse(iframe, file);
688 // get ready for next request