2 * http://github.com/valums/file-uploader
4 * Multiple file upload component with progress-bar, drag-and-drop.
5 * © 2010 Andrew Valums ( andrew(at)valums.com )
7 * Licensed under GNU GPL 2 or later and GNU LGPL 2 or later, see license.txt.
17 * Adds all missing properties from second obj to first obj
19 qq.extend = function(first, second){
20 for (var prop in second){
21 first[prop] = second[prop];
26 * Searches for a given element in the array, returns -1 if it is not present.
27 * @param {Number} [from] The index at which to begin the search
29 qq.indexOf = function(arr, elt, from){
30 if (arr.indexOf) return arr.indexOf(elt, from);
35 if (from < 0) from += len;
37 for (; from < len; from++){
38 if (from in arr && arr[from] === elt){
45 qq.getUniqueId = (function(){
47 return function(){ return id++; };
53 qq.attach = function(element, type, fn){
54 if (element.addEventListener){
55 element.addEventListener(type, fn, false);
56 } else if (element.attachEvent){
57 element.attachEvent('on' + type, fn);
60 qq.detach = function(element, type, fn){
61 if (element.removeEventListener){
62 element.removeEventListener(type, fn, false);
63 } else if (element.attachEvent){
64 element.detachEvent('on' + type, fn);
68 qq.preventDefault = function(e){
69 if (e.preventDefault){
72 e.returnValue = false;
80 * Insert node a before node b.
82 qq.insertBefore = function(a, b){
83 b.parentNode.insertBefore(a, b);
85 qq.remove = function(element){
86 element.parentNode.removeChild(element);
89 qq.contains = function(parent, descendant){
90 // compareposition returns false in this case
91 if (parent == descendant) return true;
94 return parent.contains(descendant);
96 return !!(descendant.compareDocumentPosition(parent) & 8);
101 * Creates and returns element from html string
102 * Uses innerHTML to create an element
104 qq.toElement = (function(){
105 var div = document.createElement('div');
106 return function(html){
107 div.innerHTML = html;
108 var element = div.firstChild;
109 div.removeChild(element);
115 // Node properties and attributes
118 * Sets styles for an element.
119 * Fixes opacity in IE6-8.
121 qq.css = function(element, styles){
122 if (styles.opacity != null){
123 if (typeof element.style.opacity != 'string' && typeof(element.filters) != 'undefined'){
124 styles.filter = 'alpha(opacity=' + Math.round(100 * styles.opacity) + ')';
127 qq.extend(element.style, styles);
129 qq.hasClass = function(element, name){
130 var re = new RegExp('(^| )' + name + '( |$)');
131 return re.test(element.className);
133 qq.addClass = function(element, name){
134 if (!qq.hasClass(element, name)){
135 element.className += ' ' + name;
138 qq.removeClass = function(element, name){
139 var re = new RegExp('(^| )' + name + '( |$)');
140 element.className = element.className.replace(re, ' ').replace(/^\s+|\s+$/g, "");
142 qq.setText = function(element, text){
143 element.innerText = text;
144 element.textContent = text;
148 // Selecting elements
150 qq.children = function(element){
152 child = element.firstChild;
155 if (child.nodeType == 1){
156 children.push(child);
158 child = child.nextSibling;
164 qq.getByClass = function(element, className){
165 if (element.querySelectorAll){
166 return element.querySelectorAll('.' + className);
170 var candidates = element.getElementsByTagName("*");
171 var len = candidates.length;
173 for (var i = 0; i < len; i++){
174 if (qq.hasClass(candidates[i], className)){
175 result.push(candidates[i]);
182 * obj2url() takes a json-object as argument and generates
183 * a querystring. pretty much like jQuery.param()
187 * `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');`
191 * `http://any.url/upload?otherParam=value&a=b&c=d`
193 * @param Object JSON-Object
194 * @param String current querystring-part
195 * @return String encoded querystring
197 qq.obj2url = function(obj, temp, prefixDone){
200 add = function(nextObj, i){
202 ? (/\[\]$/.test(temp)) // prevent double-encoding
206 if ((nextTemp != 'undefined') && (i != 'undefined')) {
208 (typeof nextObj === 'object')
209 ? qq.obj2url(nextObj, nextTemp, true)
210 : (Object.prototype.toString.call(nextObj) === '[object Function]')
211 ? encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj())
212 : encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj)
217 if (!prefixDone && temp) {
218 prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? '' : '&' : '?';
219 uristrings.push(temp);
220 uristrings.push(qq.obj2url(obj));
221 } else if ((Object.prototype.toString.call(obj) === '[object Array]') && (typeof obj != 'undefined') ) {
222 // we wont use a for-in-loop on an array (performance)
223 for (var i = 0, len = obj.length; i < len; ++i){
226 } else if ((typeof obj != 'undefined') && (obj !== null) && (typeof obj === "object")){
227 // for anything else but a scalar, we will use for-in-loop
229 if(obj.hasOwnProperty(i) && typeof obj[i] != 'function') {
234 uristrings.push(encodeURIComponent(temp) + '=' + encodeURIComponent(obj));
237 return uristrings.join(prefix)
239 .replace(/%20/g, '+');
251 * Creates upload button, validates upload, but doesn't create file list or dd.
253 qq.FileUploaderBasic = function(o){
255 // set to true to see the server response
257 action: '/server/upload',
263 allowedExtensions: [],
267 // return false to cancel submit
268 onSubmit: function(id, fileName){},
269 onProgress: function(id, fileName, loaded, total){},
270 onComplete: function(id, fileName, responseJSON){},
271 onCancel: function(id, fileName){},
274 typeError: "{file} has invalid extension. Only {extensions} are allowed.",
275 sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
276 minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
277 emptyError: "{file} is empty, please select files again without it.",
278 onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."
280 showMessage: function(message){
284 qq.extend(this._options, o);
286 // number of files being uploaded
287 this._filesInProgress = 0;
288 this._handler = this._createUploadHandler();
290 if (this._options.button){
291 this._button = this._createUploadButton(this._options.button);
294 this._preventLeaveInProgress();
297 qq.FileUploaderBasic.prototype = {
298 setParams: function(params){
299 this._options.params = params;
301 getInProgress: function(){
302 return this._filesInProgress;
304 _createUploadButton: function(element){
307 return new qq.UploadButton({
309 multiple: this._options.multiple && qq.UploadHandlerXhr.isSupported(),
310 onChange: function(input){
311 self._onInputChange(input);
315 _createUploadHandler: function(){
319 if(qq.UploadHandlerXhr.isSupported()){
320 handlerClass = 'UploadHandlerXhr';
322 handlerClass = 'UploadHandlerForm';
325 var handler = new qq[handlerClass]({
326 debug: this._options.debug,
327 action: this._options.action,
328 maxConnections: this._options.maxConnections,
329 onProgress: function(id, fileName, loaded, total){
330 self._onProgress(id, fileName, loaded, total);
331 self._options.onProgress(id, fileName, loaded, total);
333 onComplete: function(id, fileName, result){
334 self._onComplete(id, fileName, result);
335 self._options.onComplete(id, fileName, result);
337 onCancel: function(id, fileName){
338 self._onCancel(id, fileName);
339 self._options.onCancel(id, fileName);
345 _preventLeaveInProgress: function(){
348 qq.attach(window, 'beforeunload', function(e){
349 if (!self._filesInProgress){return;}
351 var e = e || window.event;
353 e.returnValue = self._options.messages.onLeave;
355 return self._options.messages.onLeave;
358 _onSubmit: function(id, fileName){
359 this._filesInProgress++;
361 _onProgress: function(id, fileName, loaded, total){
363 _onComplete: function(id, fileName, result){
364 this._filesInProgress--;
366 this._options.showMessage(result.error);
369 _onCancel: function(id, fileName){
370 this._filesInProgress--;
372 _onInputChange: function(input){
373 if (this._handler instanceof qq.UploadHandlerXhr){
374 this._uploadFileList(input.files);
376 if (this._validateFile(input)){
377 this._uploadFile(input);
380 this._button.reset();
382 _uploadFileList: function(files){
383 for (var i=0; i<files.length; i++){
384 if ( !this._validateFile(files[i])){
389 for (var i=0; i<files.length; i++){
390 this._uploadFile(files[i]);
393 _uploadFile: function(fileContainer){
394 var id = this._handler.add(fileContainer);
395 var fileName = this._handler.getName(id);
397 if (this._options.onSubmit(id, fileName) !== false){
398 this._onSubmit(id, fileName);
399 this._handler.upload(id, this._options.params);
402 _validateFile: function(file){
406 // it is a file input
407 // get input value and remove path to normalize
408 name = file.value.replace(/.*(\/|\\)/, "");
410 // fix missing properties in Safari
411 name = file.fileName != null ? file.fileName : file.name;
412 size = file.fileSize != null ? file.fileSize : file.size;
415 if (! this._isAllowedExtension(name)){
416 this._error('typeError', name);
419 } else if (size === 0){
420 this._error('emptyError', name);
423 } else if (size && this._options.sizeLimit && size > this._options.sizeLimit){
424 this._error('sizeError', name);
427 } else if (size && size < this._options.minSizeLimit){
428 this._error('minSizeError', name);
434 _error: function(code, fileName){
435 var message = this._options.messages[code];
436 function r(name, replacement){ message = message.replace(name, replacement); }
438 r('{file}', this._formatFileName(fileName));
439 r('{extensions}', this._options.allowedExtensions.join(', '));
440 r('{sizeLimit}', this._formatSize(this._options.sizeLimit));
441 r('{minSizeLimit}', this._formatSize(this._options.minSizeLimit));
443 this._options.showMessage(message);
445 _formatFileName: function(name){
446 if (name.length > 33){
447 name = name.slice(0, 19) + '...' + name.slice(-13);
451 _isAllowedExtension: function(fileName){
452 var ext = (-1 !== fileName.indexOf('.')) ? fileName.replace(/.*[.]/, '').toLowerCase() : '';
453 var allowed = this._options.allowedExtensions;
455 if (!allowed.length){return true;}
457 for (var i=0; i<allowed.length; i++){
458 if (allowed[i].toLowerCase() == ext){ return true;}
463 _formatSize: function(bytes){
466 bytes = bytes / 1024;
468 } while (bytes > 99);
470 return Math.max(bytes, 0.1).toFixed(1) + ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i];
476 * Class that creates upload widget with drag-and-drop and file list
477 * @inherits qq.FileUploaderBasic
479 qq.FileUploader = function(o){
480 // call parent constructor
481 qq.FileUploaderBasic.apply(this, arguments);
483 // additional options
484 qq.extend(this._options, {
486 // if set, will be used instead of qq-upload-list in template
489 template: '<div class="qq-uploader">' +
490 '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
491 '<div class="qq-upload-button">Upload a file</div>' +
492 '<ul class="qq-upload-list"></ul>' +
495 // template for one item in file list
496 fileTemplate: '<li>' +
497 '<span class="qq-upload-file"></span>' +
498 '<span class="qq-upload-spinner"></span>' +
499 '<span class="qq-upload-size"></span>' +
500 '<a class="qq-upload-cancel" href="#">Cancel</a>' +
501 '<span class="qq-upload-failed-text">Failed</span>' +
505 // used to get elements from templates
506 button: 'qq-upload-button',
507 drop: 'qq-upload-drop-area',
508 dropActive: 'qq-upload-drop-area-active',
509 list: 'qq-upload-list',
511 file: 'qq-upload-file',
512 spinner: 'qq-upload-spinner',
513 size: 'qq-upload-size',
514 cancel: 'qq-upload-cancel',
516 // added to list item when upload completes
517 // used in css to hide progress spinner
518 success: 'qq-upload-success',
519 fail: 'qq-upload-fail'
522 // overwrite options with user supplied
523 qq.extend(this._options, o);
525 this._element = this._options.element;
526 this._element.innerHTML = this._options.template;
527 this._listElement = this._options.listElement || this._find(this._element, 'list');
529 this._classes = this._options.classes;
531 this._button = this._createUploadButton(this._find(this._element, 'button'));
533 this._bindCancelEvent();
534 this._setupDragDrop();
537 // inherit from Basic Uploader
538 qq.extend(qq.FileUploader.prototype, qq.FileUploaderBasic.prototype);
540 qq.extend(qq.FileUploader.prototype, {
542 * Gets one of the elements listed in this._options.classes
544 _find: function(parent, type){
545 var element = qq.getByClass(parent, this._options.classes[type])[0];
547 throw new Error('element not found ' + type);
552 _setupDragDrop: function(){
554 dropArea = this._find(this._element, 'drop');
556 var dz = new qq.UploadDropZone({
558 onEnter: function(e){
559 qq.addClass(dropArea, self._classes.dropActive);
562 onLeave: function(e){
565 onLeaveNotDescendants: function(e){
566 qq.removeClass(dropArea, self._classes.dropActive);
569 dropArea.style.display = 'none';
570 qq.removeClass(dropArea, self._classes.dropActive);
571 self._uploadFileList(e.dataTransfer.files);
575 dropArea.style.display = 'none';
577 qq.attach(document, 'dragenter', function(e){
578 if (!dz._isValidFileDrag(e)) return;
580 dropArea.style.display = 'block';
582 qq.attach(document, 'dragleave', function(e){
583 if (!dz._isValidFileDrag(e)) return;
585 var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
586 // only fire when leaving document out
587 if ( ! relatedTarget || relatedTarget.nodeName == "HTML"){
588 dropArea.style.display = 'none';
592 _onSubmit: function(id, fileName){
593 qq.FileUploaderBasic.prototype._onSubmit.apply(this, arguments);
594 this._addToList(id, fileName);
596 _onProgress: function(id, fileName, loaded, total){
597 qq.FileUploaderBasic.prototype._onProgress.apply(this, arguments);
599 var item = this._getItemByFileId(id);
600 var size = this._find(item, 'size');
601 size.style.display = 'inline';
604 if (loaded != total){
605 text = Math.round(loaded / total * 100) + '% from ' + this._formatSize(total);
607 text = this._formatSize(total);
610 qq.setText(size, text);
612 _onComplete: function(id, fileName, result){
613 qq.FileUploaderBasic.prototype._onComplete.apply(this, arguments);
616 var item = this._getItemByFileId(id);
617 qq.remove(this._find(item, 'cancel'));
618 qq.remove(this._find(item, 'spinner'));
621 qq.addClass(item, this._classes.success);
623 qq.addClass(item, this._classes.fail);
626 _addToList: function(id, fileName){
627 var item = qq.toElement(this._options.fileTemplate);
630 var fileElement = this._find(item, 'file');
631 qq.setText(fileElement, this._formatFileName(fileName));
632 this._find(item, 'size').style.display = 'none';
634 this._listElement.appendChild(item);
636 _getItemByFileId: function(id){
637 var item = this._listElement.firstChild;
639 // there can't be txt nodes in dynamically created list
640 // and we can use nextSibling
642 if (item.qqFileId == id) return item;
643 item = item.nextSibling;
647 * delegate click event for cancel link
649 _bindCancelEvent: function(){
651 list = this._listElement;
653 qq.attach(list, 'click', function(e){
654 e = e || window.event;
655 var target = e.target || e.srcElement;
657 if (qq.hasClass(target, self._classes.cancel)){
658 qq.preventDefault(e);
660 var item = target.parentNode;
661 self._handler.cancel(item.qqFileId);
668 qq.UploadDropZone = function(o){
671 onEnter: function(e){},
672 onLeave: function(e){},
673 // is not fired when leaving element by hovering descendants
674 onLeaveNotDescendants: function(e){},
675 onDrop: function(e){}
677 qq.extend(this._options, o);
679 this._element = this._options.element;
681 this._disableDropOutside();
682 this._attachEvents();
685 qq.UploadDropZone.prototype = {
686 _disableDropOutside: function(e){
687 // run only once for all instances
688 if (!qq.UploadDropZone.dropOutsideDisabled ){
690 qq.attach(document, 'dragover', function(e){
692 e.dataTransfer.dropEffect = 'none';
697 qq.UploadDropZone.dropOutsideDisabled = true;
700 _attachEvents: function(){
703 qq.attach(self._element, 'dragover', function(e){
704 if (!self._isValidFileDrag(e)) return;
706 var effect = e.dataTransfer.effectAllowed;
707 if (effect == 'move' || effect == 'linkMove'){
708 e.dataTransfer.dropEffect = 'move'; // for FF (only move allowed)
710 e.dataTransfer.dropEffect = 'copy'; // for Chrome
717 qq.attach(self._element, 'dragenter', function(e){
718 if (!self._isValidFileDrag(e)) return;
720 self._options.onEnter(e);
723 qq.attach(self._element, 'dragleave', function(e){
724 if (!self._isValidFileDrag(e)) return;
726 self._options.onLeave(e);
728 var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
729 // do not fire when moving a mouse over a descendant
730 if (qq.contains(this, relatedTarget)) return;
732 self._options.onLeaveNotDescendants(e);
735 qq.attach(self._element, 'drop', function(e){
736 if (!self._isValidFileDrag(e)) return;
739 self._options.onDrop(e);
742 _isValidFileDrag: function(e){
743 var dt = e.dataTransfer,
744 // do not check dt.types.contains in webkit, because it crashes safari 4
745 isWebkit = navigator.userAgent.indexOf("AppleWebKit") > -1;
747 // dt.effectAllowed is none in Safari 5
748 // dt.types.contains check is for firefox
749 return dt && dt.effectAllowed != 'none' &&
750 (dt.files || (!isWebkit && dt.types.contains && dt.types.contains('Files')));
755 qq.UploadButton = function(o){
758 // if set to true adds multiple attribute to file input
760 // name attribute of file input
762 onChange: function(input){},
763 hoverClass: 'qq-upload-button-hover',
764 focusClass: 'qq-upload-button-focus'
767 qq.extend(this._options, o);
769 this._element = this._options.element;
771 // make button suitable container for input
772 qq.css(this._element, {
773 position: 'relative',
775 // Make sure browse button is in the right side
776 // in Internet Explorer
780 this._input = this._createInput();
783 qq.UploadButton.prototype = {
784 /* returns file input element */
785 getInput: function(){
788 /* cleans/recreates the file input */
790 if (this._input.parentNode){
791 qq.remove(this._input);
794 qq.removeClass(this._element, this._options.focusClass);
795 this._input = this._createInput();
797 _createInput: function(){
798 var input = document.createElement("input");
800 if (this._options.multiple){
801 input.setAttribute("multiple", "multiple");
804 input.setAttribute("type", "file");
805 input.setAttribute("name", this._options.name);
808 position: 'absolute',
809 // in Opera only 'browse' button
810 // is clickable and it is located at
811 // the right side of the input
815 // 4 persons reported this, the max values that worked for them were 243, 236, 236, 118
823 this._element.appendChild(input);
826 qq.attach(input, 'change', function(){
827 self._options.onChange(input);
830 qq.attach(input, 'mouseover', function(){
831 qq.addClass(self._element, self._options.hoverClass);
833 qq.attach(input, 'mouseout', function(){
834 qq.removeClass(self._element, self._options.hoverClass);
836 qq.attach(input, 'focus', function(){
837 qq.addClass(self._element, self._options.focusClass);
839 qq.attach(input, 'blur', function(){
840 qq.removeClass(self._element, self._options.focusClass);
843 // IE and Opera, unfortunately have 2 tab stops on file input
844 // which is unacceptable in our case, disable keyboard access
845 if (window.attachEvent){
847 input.setAttribute('tabIndex', "-1");
855 * Class for uploading files, uploading itself is handled by child classes
857 qq.UploadHandlerAbstract = function(o){
860 action: '/upload.php',
861 // maximum number of concurrent uploads
863 onProgress: function(id, fileName, loaded, total){},
864 onComplete: function(id, fileName, response){},
865 onCancel: function(id, fileName){}
867 qq.extend(this._options, o);
870 // params for files in queue
873 qq.UploadHandlerAbstract.prototype = {
875 if (this._options.debug && window.console) console.log('[uploader] ' + str);
878 * Adds file or file input to the queue
881 add: function(file){},
883 * Sends the file identified by id and additional query params to the server
885 upload: function(id, params){
886 var len = this._queue.push(id);
889 qq.extend(copy, params);
890 this._params[id] = copy;
892 // if too many active uploads, wait...
893 if (len <= this._options.maxConnections){
894 this._upload(id, this._params[id]);
898 * Cancels file upload by id
900 cancel: function(id){
905 * Cancells all uploads
907 cancelAll: function(){
908 for (var i=0; i<this._queue.length; i++){
909 this._cancel(this._queue[i]);
914 * Returns name of the file identified by id
916 getName: function(id){},
918 * Returns size of the file identified by id
920 getSize: function(id){},
922 * Returns id of files being uploaded or
923 * waiting for their turn
925 getQueue: function(){
929 * Actual upload method
931 _upload: function(id){},
933 * Actual cancel method
935 _cancel: function(id){},
937 * Removes element from queue, starts upload of next
939 _dequeue: function(id){
940 var i = qq.indexOf(this._queue, id);
941 this._queue.splice(i, 1);
943 var max = this._options.maxConnections;
945 if (this._queue.length >= max && i < max){
946 var nextId = this._queue[max-1];
947 this._upload(nextId, this._params[nextId]);
953 * Class for uploading files using form and iframe
954 * @inherits qq.UploadHandlerAbstract
956 qq.UploadHandlerForm = function(o){
957 qq.UploadHandlerAbstract.apply(this, arguments);
961 // @inherits qq.UploadHandlerAbstract
962 qq.extend(qq.UploadHandlerForm.prototype, qq.UploadHandlerAbstract.prototype);
964 qq.extend(qq.UploadHandlerForm.prototype, {
965 add: function(fileInput){
966 fileInput.setAttribute('name', 'qqfile');
967 var id = 'qq-upload-handler-iframe' + qq.getUniqueId();
969 this._inputs[id] = fileInput;
971 // remove file input from DOM
972 if (fileInput.parentNode){
973 qq.remove(fileInput);
978 getName: function(id){
979 // get input value and remove path to normalize
980 return this._inputs[id].value.replace(/.*(\/|\\)/, "");
982 _cancel: function(id){
983 this._options.onCancel(id, this.getName(id));
985 delete this._inputs[id];
987 var iframe = document.getElementById(id);
989 // to cancel request set src to something else
990 // we use src="javascript:false;" because it doesn't
991 // trigger ie6 prompt on https
992 iframe.setAttribute('src', 'javascript:false;');
997 _upload: function(id, params){
998 var input = this._inputs[id];
1001 throw new Error('file with passed id was not added, or already uploaded or cancelled');
1004 var fileName = this.getName(id);
1006 var iframe = this._createIframe(id);
1007 var form = this._createForm(iframe, params);
1008 form.appendChild(input);
1011 this._attachLoadEvent(iframe, function(){
1012 self.log('iframe loaded');
1014 var response = self._getIframeContentJSON(iframe);
1016 self._options.onComplete(id, fileName, response);
1019 delete self._inputs[id];
1020 // timeout added to fix busy state in FF3.6
1021 setTimeout(function(){
1031 _attachLoadEvent: function(iframe, callback){
1032 qq.attach(iframe, 'load', function(){
1033 // when we remove iframe from dom
1034 // the request stops, but in IE load
1036 if (!iframe.parentNode){
1040 // fixing Opera 10.53
1041 if (iframe.contentDocument &&
1042 iframe.contentDocument.body &&
1043 iframe.contentDocument.body.innerHTML == "false"){
1044 // In Opera event is fired second time
1045 // when body.innerHTML changed from false
1046 // to server response approx. after 1 sec
1047 // when we upload file with iframe
1055 * Returns json object received by iframe from server.
1057 _getIframeContentJSON: function(iframe){
1058 // iframe.contentWindow.document - for IE<7
1059 var doc = iframe.contentDocument ? iframe.contentDocument: iframe.contentWindow.document,
1062 this.log("converting iframe's innerHTML to JSON");
1063 this.log("innerHTML = " + doc.body.innerHTML);
1066 response = eval("(" + doc.body.innerHTML + ")");
1074 * Creates iframe with unique name
1076 _createIframe: function(id){
1077 // We can't use following code as the name attribute
1078 // won't be properly registered in IE6, and new window
1079 // on form submit will open
1080 // var iframe = document.createElement('iframe');
1081 // iframe.setAttribute('name', id);
1083 var iframe = qq.toElement('<iframe src="javascript:false;" name="' + id + '" />');
1084 // src="javascript:false;" removes ie6 prompt on https
1086 iframe.setAttribute('id', id);
1088 iframe.style.display = 'none';
1089 document.body.appendChild(iframe);
1094 * Creates form, that will be submitted to iframe
1096 _createForm: function(iframe, params){
1097 // We can't use the following code in IE6
1098 // var form = document.createElement('form');
1099 // form.setAttribute('method', 'post');
1100 // form.setAttribute('enctype', 'multipart/form-data');
1101 // Because in this case file won't be attached to request
1102 var form = qq.toElement('<form method="post" enctype="multipart/form-data"></form>');
1104 var queryString = qq.obj2url(params, this._options.action);
1106 form.setAttribute('action', queryString);
1107 form.setAttribute('target', iframe.name);
1108 form.style.display = 'none';
1109 document.body.appendChild(form);
1116 * Class for uploading files using xhr
1117 * @inherits qq.UploadHandlerAbstract
1119 qq.UploadHandlerXhr = function(o){
1120 qq.UploadHandlerAbstract.apply(this, arguments);
1125 // current loaded size in bytes for each file
1130 qq.UploadHandlerXhr.isSupported = function(){
1131 var input = document.createElement('input');
1132 input.type = 'file';
1135 'multiple' in input &&
1136 typeof File != "undefined" &&
1137 typeof (new XMLHttpRequest()).upload != "undefined" );
1140 // @inherits qq.UploadHandlerAbstract
1141 qq.extend(qq.UploadHandlerXhr.prototype, qq.UploadHandlerAbstract.prototype);
1143 qq.extend(qq.UploadHandlerXhr.prototype, {
1145 * Adds file to the queue
1146 * Returns id to use with upload, cancel
1148 add: function(file){
1149 if (!(file instanceof File)){
1150 throw new Error('Passed obj in not a File (in qq.UploadHandlerXhr)');
1153 return this._files.push(file) - 1;
1155 getName: function(id){
1156 var file = this._files[id];
1157 // fix missing name in Safari 4
1158 return file.fileName != null ? file.fileName : file.name;
1160 getSize: function(id){
1161 var file = this._files[id];
1162 return file.fileSize != null ? file.fileSize : file.size;
1165 * Returns uploaded bytes for file identified by id
1167 getLoaded: function(id){
1168 return this._loaded[id] || 0;
1171 * Sends the file identified by id and additional query params to the server
1172 * @param {Object} params name-value string pairs
1174 _upload: function(id, params){
1175 var file = this._files[id],
1176 name = this.getName(id),
1177 size = this.getSize(id);
1179 this._loaded[id] = 0;
1181 var xhr = this._xhrs[id] = new XMLHttpRequest();
1184 xhr.upload.onprogress = function(e){
1185 if (e.lengthComputable){
1186 self._loaded[id] = e.loaded;
1187 self._options.onProgress(id, name, e.loaded, e.total);
1191 xhr.onreadystatechange = function(){
1192 if (xhr.readyState == 4){
1193 self._onComplete(id, xhr);
1197 // build query string
1198 params = params || {};
1199 params['qqfile'] = name;
1200 var queryString = qq.obj2url(params, this._options.action);
1202 xhr.open("POST", queryString, true);
1203 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
1204 xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
1205 xhr.setRequestHeader("Content-Type", "application/octet-stream");
1208 _onComplete: function(id, xhr){
1209 // the request was aborted/cancelled
1210 if (!this._files[id]) return;
1212 var name = this.getName(id);
1213 var size = this.getSize(id);
1215 this._options.onProgress(id, name, size, size);
1217 if (xhr.status == 200){
1218 this.log("xhr - server response received");
1219 this.log("responseText = " + xhr.responseText);
1224 response = eval("(" + xhr.responseText + ")");
1229 this._options.onComplete(id, name, response);
1232 this._options.onComplete(id, name, {});
1235 this._files[id] = null;
1236 this._xhrs[id] = null;
1239 _cancel: function(id){
1240 this._options.onCancel(id, this.getName(id));
1242 this._files[id] = null;
1244 if (this._xhrs[id]){
1245 this._xhrs[id].abort();
1246 this._xhrs[id] = null;