Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Alter form to utilize options.inputName instead of filename when encoding is set to multipart #37

Merged
merged 1 commit into from

2 participants

@ebrentnelson
Owner

Applicable change is on line 1352 (everything else is line ending whitespace removal).

It make sense that the form being submitted would utilize the inputName specified in the options.

@SimonEast
Owner

Hi Brent, we don't really have an active maintainer here to test and accept your merge. Let us know if you would like to help maintain this repo.

@ebrentnelson
Owner
@ebrentnelson ebrentnelson merged commit 9258f3c into Valums-File-Uploader:master
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Nov 5, 2013
  1. @ebrentnelson
This page is out of date. Refresh to see the latest.
Showing with 288 additions and 288 deletions.
  1. +288 −288 client/fileuploader.js
View
576 client/fileuploader.js
@@ -1,13 +1,13 @@
/**
* http://github.com/Valums-File-Uploader/file-uploader
- *
- * Multiple file upload component with progress-bar, drag-and-drop.
- *
- * Have ideas for improving this JS for the general community?
+ *
+ * Multiple file upload component with progress-bar, drag-and-drop.
+ *
+ * Have ideas for improving this JS for the general community?
* Submit your changes at: https://github.com/Valums-File-Uploader/file-uploader
*
* VERSION 2.0 beta
- * Original version 1.0 © 2010 Andrew Valums ( andrew(at)valums.com )
+ * Original version 1.0 © 2010 Andrew Valums ( andrew(at)valums.com )
* Licensed under GNU GPL 2 or later and GNU LGPL 2 or later, see license.txt.
*/
@@ -19,12 +19,12 @@ var qq = qq || {};
/**
* Adds all missing properties from second obj to first obj
- */
+ */
qq.extend = function(first, second){
for (var prop in second){
first[prop] = second[prop];
}
-};
+};
/**
* Searches for a given element in the array, returns -1 if it is not present.
@@ -32,20 +32,20 @@ qq.extend = function(first, second){
*/
qq.indexOf = function(arr, elt, from){
if (arr.indexOf) return arr.indexOf(elt, from);
-
+
from = from || 0;
- var len = arr.length;
-
- if (from < 0) from += len;
+ var len = arr.length;
+
+ if (from < 0) from += len;
- for (; from < len; from++){
- if (from in arr && arr[from] === elt){
+ for (; from < len; from++){
+ if (from in arr && arr[from] === elt){
return from;
}
- }
- return -1;
-};
-
+ }
+ return -1;
+};
+
qq.getUniqueId = (function(){
var id = 0;
return function(){ return id++; };
@@ -53,7 +53,7 @@ qq.getUniqueId = (function(){
//
// Browsers and platforms detection
-
+
qq.ie = function(){ return navigator.userAgent.indexOf('MSIE') != -1; };
qq.safari = function(){ return navigator.vendor != undefined && navigator.vendor.indexOf("Apple") != -1; };
qq.chrome = function(){ return navigator.vendor != undefined && navigator.vendor.indexOf('Google') != -1; };
@@ -103,10 +103,10 @@ qq.remove = function(element){
element.parentNode.removeChild(element);
};
-qq.contains = function(parent, descendant){
+qq.contains = function(parent, descendant){
// compareposition returns false in this case
if (parent == descendant) return true;
-
+
if (parent.contains){
return parent.contains(descendant);
} else {
@@ -198,7 +198,7 @@ qq.getByClass = function(element, className){
/**
* obj2url() takes a json-object as argument and generates
* a querystring. pretty much like jQuery.param()
- *
+ *
* how to use:
*
* `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');`
@@ -215,21 +215,21 @@ qq.obj2url = function(obj, temp, prefixDone){
var uristrings = [],
prefix = '&',
add = function(nextObj, i){
- var nextTemp = temp
+ var nextTemp = temp
? (/\[\]$/.test(temp)) // prevent double-encoding
? temp
: temp+'['+i+']'
: i;
- if ((nextTemp != 'undefined') && (i != 'undefined')) {
+ if ((nextTemp != 'undefined') && (i != 'undefined')) {
uristrings.push(
- (typeof nextObj === 'object')
+ (typeof nextObj === 'object')
? qq.obj2url(nextObj, nextTemp, true)
: (Object.prototype.toString.call(nextObj) === '[object Function]')
? encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj())
- : encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj)
+ : encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj)
);
}
- };
+ };
if (!prefixDone && temp) {
prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? '' : '&' : '?';
@@ -251,7 +251,7 @@ qq.obj2url = function(obj, temp, prefixDone){
return uristrings.join(prefix)
.replace(/^&/, '')
- .replace(/%20/g, '+');
+ .replace(/%20/g, '+');
};
//
@@ -261,9 +261,9 @@ qq.obj2url = function(obj, temp, prefixDone){
//
var qq = qq || {};
-
+
/**
- * Creates upload button, validates upload, but doesn't create file list or dd.
+ * Creates upload button, validates upload, but doesn't create file list or dd.
*/
qq.FileUploaderBasic = function(o){
this._options = {
@@ -275,11 +275,11 @@ qq.FileUploaderBasic = function(o){
button: null,
multiple: true,
maxConnections: 3,
- // validation
+ // validation
allowedExtensions: [],
acceptFiles: null, // comma separated string of mime-types for browser to display in browse dialog
- sizeLimit: 0,
- minSizeLimit: 0,
+ sizeLimit: 0,
+ minSizeLimit: 0,
abortOnFailure: true, // Fail all files if one doesn't meet the criteria
// events
// return false to cancel submit
@@ -289,13 +289,13 @@ qq.FileUploaderBasic = function(o){
onCancel: function(id, fileName){},
onUpload: function(id, fileName, xhr){},
onError: function(id, fileName, xhr) {},
- // messages
+ // messages
messages: {
typeError: "Unfortunately the file(s) you selected weren't the type we were expecting. Only {extensions} files are allowed.",
sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
emptyError: "{file} is empty, please select files again without it.",
- onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."
+ onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."
},
showMessage: function(message){
alert(message);
@@ -309,42 +309,42 @@ qq.FileUploaderBasic = function(o){
// number of files being uploaded
this._filesInProgress = 0;
this._handler = this._createUploadHandler();
-
- if (this._options.button){
+
+ if (this._options.button){
this._button = this._createUploadButton(this._options.button);
}
-
- this._preventLeaveInProgress();
+
+ this._preventLeaveInProgress();
};
-
+
qq.FileUploaderBasic.prototype = {
setParams: function(params){
this._options.params = params;
},
getInProgress: function(){
- return this._filesInProgress;
+ return this._filesInProgress;
},
_createUploadButton: function(element){
var self = this;
-
+
var button = new qq.UploadButton({
element: element,
multiple: this._options.multiple && qq.UploadHandlerXhr.isSupported(),
acceptFiles: this._options.acceptFiles,
onChange: function(input){
self._onInputChange(input);
- }
+ }
});
this.addDisposer(function() { button.dispose(); });
return button;
- },
+ },
_createUploadHandler: function(){
var self = this,
- handlerClass;
-
- if(qq.UploadHandlerXhr.isSupported()){
- handlerClass = 'UploadHandlerXhr';
+ handlerClass;
+
+ if(qq.UploadHandlerXhr.isSupported()){
+ handlerClass = 'UploadHandlerXhr';
} else {
handlerClass = 'UploadHandlerForm';
}
@@ -353,14 +353,14 @@ qq.FileUploaderBasic.prototype = {
debug: this._options.debug,
action: this._options.action,
encoding: this._options.encoding,
- maxConnections: this._options.maxConnections,
+ maxConnections: this._options.maxConnections,
customHeaders: this._options.customHeaders,
inputName: this._options.inputName,
extraDropzones: this._options.extraDropzones,
- onProgress: function(id, fileName, loaded, total){
+ onProgress: function(id, fileName, loaded, total){
self._onProgress(id, fileName, loaded, total);
- self._options.onProgress(id, fileName, loaded, total);
- },
+ self._options.onProgress(id, fileName, loaded, total);
+ },
onComplete: function(id, fileName, result){
self._onComplete(id, fileName, result);
self._options.onComplete(id, fileName, result);
@@ -377,46 +377,46 @@ qq.FileUploaderBasic.prototype = {
});
return handler;
- },
+ },
_preventLeaveInProgress: function(){
var self = this;
-
+
this._attach(window, 'beforeunload', function(e){
if (!self._filesInProgress){return;}
-
+
var e = e || window.event;
// for ie, ff
e.returnValue = self._options.messages.onLeave;
// for webkit
- return self._options.messages.onLeave;
- });
+ return self._options.messages.onLeave;
+ });
},
_onSubmit: function(id, fileName){
- this._filesInProgress++;
+ this._filesInProgress++;
},
- _onProgress: function(id, fileName, loaded, total){
+ _onProgress: function(id, fileName, loaded, total){
},
_onComplete: function(id, fileName, result){
- this._filesInProgress--;
+ this._filesInProgress--;
if (result.error){
this._options.showMessage(result.error);
- }
+ }
},
_onCancel: function(id, fileName){
- this._filesInProgress--;
+ this._filesInProgress--;
},
- _onUpload: function(id, fileName, xhr){
+ _onUpload: function(id, fileName, xhr){
},
_onInputChange: function(input){
- if (this._handler instanceof qq.UploadHandlerXhr){
- this._uploadFileList(input.files);
- } else {
- if (this._validateFile(input)){
- this._uploadFile(input);
- }
- }
- this._button.reset();
- },
+ if (this._handler instanceof qq.UploadHandlerXhr){
+ this._uploadFileList(input.files);
+ } else {
+ if (this._validateFile(input)){
+ this._uploadFile(input);
+ }
+ }
+ this._button.reset();
+ },
_uploadFileList: function(files){
var goodFiles = [];
for (var i=0; i<files.length; i++){
@@ -426,25 +426,25 @@ qq.FileUploaderBasic.prototype = {
if (this._options.abortOnFailure) return;
}
}
-
+
for (var i=0; i<goodFiles.length; i++){
this._uploadFile(goodFiles[i]);
- }
- },
- _uploadFile: function(fileContainer){
+ }
+ },
+ _uploadFile: function(fileContainer){
var id = this._handler.add(fileContainer);
var fileName = this._handler.getName(id);
-
+
if (this._options.onSubmit(id, fileName) !== false){
this._onSubmit(id, fileName);
this._handler.upload(id, this._options.params);
}
- },
+ },
_validateFile: function(file){
var name, size;
-
+
if (file.value){
- // it is a file input
+ // it is a file input
// get input value and remove path to normalize
name = file.value.replace(/.*(\/|\\)/, "");
} else {
@@ -452,69 +452,69 @@ qq.FileUploaderBasic.prototype = {
name = (file.fileName !== null && file.fileName !== undefined) ? file.fileName : file.name;
size = (file.fileSize !== null && file.fileSize !== undefined) ? file.fileSize : file.size;
}
-
- if (! this._isAllowedExtension(name)){
+
+ if (! this._isAllowedExtension(name)){
this._error('typeError', name);
return false;
-
- } else if (size === 0){
+
+ } else if (size === 0){
this._error('emptyError', name);
return false;
-
- } else if (size && this._options.sizeLimit && size > this._options.sizeLimit){
+
+ } else if (size && this._options.sizeLimit && size > this._options.sizeLimit){
this._error('sizeError', name);
return false;
-
+
} else if (size && size < this._options.minSizeLimit){
this._error('minSizeError', name);
- return false;
+ return false;
}
-
- return true;
+
+ return true;
},
_error: function(code, fileName){
- var message = this._options.messages[code];
+ var message = this._options.messages[code];
function r(name, replacement){ message = message.replace(name, replacement); }
-
- r('{file}', this._formatFileName(fileName));
+
+ r('{file}', this._formatFileName(fileName));
r('{extensions}', this._options.allowedExtensions.join(', '));
r('{sizeLimit}', this._formatSize(this._options.sizeLimit));
r('{minSizeLimit}', this._formatSize(this._options.minSizeLimit));
-
- this._options.showMessage(message);
+
+ this._options.showMessage(message);
},
_formatFileName: function(name){
if (name.length > 33){
- name = name.slice(0, 19) + '...' + name.slice(-13);
+ name = name.slice(0, 19) + '...' + name.slice(-13);
}
return name;
},
_isAllowedExtension: function(fileName){
- var ext = (-1 !== fileName.indexOf('.'))
- ? fileName.replace(/.*[.]/, '').toLowerCase()
+ var ext = (-1 !== fileName.indexOf('.'))
+ ? fileName.replace(/.*[.]/, '').toLowerCase()
: '';
var allowed = this._options.allowedExtensions;
-
- if (!allowed.length){return true;}
-
+
+ if (!allowed.length){return true;}
+
for (var i=0; i<allowed.length; i++){
- if (allowed[i].toLowerCase() == ext){ return true;}
+ if (allowed[i].toLowerCase() == ext){ return true;}
}
-
+
return false;
- },
+ },
_formatSize: function(bytes){
- var i = -1;
+ var i = -1;
do {
bytes = bytes / 1024;
- i++;
+ i++;
} while (bytes > 99);
-
- return Math.max(bytes, 0.1).toFixed(1) + ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i];
+
+ return Math.max(bytes, 0.1).toFixed(1) + ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i];
}
};
-
-
+
+
/**
* Class that creates upload widget with drag-and-drop and file list
* @inherits qq.FileUploaderBasic
@@ -522,22 +522,22 @@ qq.FileUploaderBasic.prototype = {
qq.FileUploader = function(o){
// call parent constructor
qq.FileUploaderBasic.apply(this, arguments);
-
- // additional options
+
+ // additional options
qq.extend(this._options, {
element: null,
// if set, will be used instead of qq-upload-list in template
listElement: null,
- dragText: 'Drop files here to upload',
- uploadButtonText: 'Upload a file',
- cancelButtonText: 'Cancel',
+ dragText: 'Drop files here to upload',
+ uploadButtonText: 'Upload a file',
+ cancelButtonText: 'Cancel',
failUploadText: 'Upload failed',
hideShowDropArea: true,
-
- template: '<div class="qq-uploader">' +
+
+ template: '<div class="qq-uploader">' +
'<div class="qq-upload-drop-area"><span>{dragText}</span></div>' +
'<div class="qq-upload-button">{uploadButtonText}</div>' +
- '<ul class="qq-upload-list"></ul>' +
+ '<ul class="qq-upload-list"></ul>' +
'</div>',
// template for one item in file list
@@ -548,8 +548,8 @@ qq.FileUploader = function(o){
'<span class="qq-upload-size"></span>' +
'<a class="qq-upload-cancel" href="#">{cancelButtonText}</a>' +
'<span class="qq-upload-failed-text">{failUploadtext}</span>' +
- '</li>',
-
+ '</li>',
+
classes: {
// used to get elements from templates
button: 'qq-upload-button',
@@ -569,9 +569,9 @@ qq.FileUploader = function(o){
fail: 'qq-upload-fail'
}
});
- // overwrite options with user supplied
+ // overwrite options with user supplied
qq.extend(this._options, o);
-
+
// overwrite the upload button text if any
// same for the Cancel button and Fail message text
this._options.template = this._options.template.replace(/\{dragText\}/g, this._options.dragText);
@@ -580,13 +580,13 @@ qq.FileUploader = function(o){
this._options.fileTemplate = this._options.fileTemplate.replace(/\{failUploadtext\}/g, this._options.failUploadText);
this._element = this._options.element;
- this._element.innerHTML = this._options.template;
+ this._element.innerHTML = this._options.template;
this._listElement = this._options.listElement || this._find(this._element, 'list');
-
+
this._classes = this._options.classes;
-
- this._button = this._createUploadButton(this._find(this._element, 'button'));
-
+
+ this._button = this._createUploadButton(this._find(this._element, 'button'));
+
this._bindCancelEvent();
this._setupDragDrop();
};
@@ -599,7 +599,7 @@ qq.extend(qq.FileUploader.prototype, {
this._setupExtraDropzone(element);
},
removeExtraDropzone: function(element){
- var dzs = this._options.extraDropzones;
+ var dzs = this._options.extraDropzones;
for(var i in dzs) if (dzs[i] === element) return this._options.extraDropzones.splice(i,1);
},
_leaving_document_out: function(e){
@@ -609,21 +609,21 @@ qq.extend(qq.FileUploader.prototype, {
/**
* Gets one of the elements listed in this._options.classes
**/
- _find: function(parent, type){
- var element = qq.getByClass(parent, this._options.classes[type])[0];
+ _find: function(parent, type){
+ var element = qq.getByClass(parent, this._options.classes[type])[0];
if (!element){
throw new Error('element not found ' + type);
}
-
+
return element;
},
_setupExtraDropzone: function(element){
- this._options.extraDropzones.push(element);
+ this._options.extraDropzones.push(element);
this._setupDropzone(element);
},
_setupDropzone: function(dropArea){
var self = this;
-
+
var dz = new qq.UploadDropZone({
element: dropArea,
onEnter: function(e){
@@ -634,14 +634,14 @@ qq.extend(qq.FileUploader.prototype, {
//e.stopPropagation();
},
onLeaveNotDescendants: function(e){
- qq.removeClass(dropArea, self._classes.dropActive);
+ qq.removeClass(dropArea, self._classes.dropActive);
},
onDrop: function(e){
if (self._options.hideShowDropArea) {
dropArea.style.display = 'none';
}
qq.removeClass(dropArea, self._classes.dropActive);
- self._uploadFileList(e.dataTransfer.files);
+ self._uploadFileList(e.dataTransfer.files);
}
});
@@ -654,14 +654,14 @@ qq.extend(qq.FileUploader.prototype, {
_setupDragDrop: function(){
var dropArea = this._find(this._element, 'drop');
var self = this;
- this._options.extraDropzones.push(dropArea);
-
+ this._options.extraDropzones.push(dropArea);
+
var dropzones = this._options.extraDropzones;
var i;
for (i=0; i < dropzones.length; i++){
this._setupDropzone(dropzones[i]);
}
-
+
// IE <= 9 does not support the File API used for drag+drop uploads
// Any volunteers to enable & test this for IE10?
if (!qq.ie()) {
@@ -670,9 +670,9 @@ qq.extend(qq.FileUploader.prototype, {
if (!self._isValidFileDrag(e)) return; // now causing error. Need it be here?
if (qq.hasClass(dropArea, self._classes.dropDisabled)) return;
- dropArea.style.display = 'block';
+ dropArea.style.display = 'block';
for (i=0; i < dropzones.length; i++){ dropzones[i].style.display = 'block'; }
-
+
});
}
this._attach(document, 'dragleave', function(e){
@@ -682,17 +682,17 @@ qq.extend(qq.FileUploader.prototype, {
qq.FileUploader.prototype._leaving_document_out(e)) {
for (i=0; i < dropzones.length; i++){ dropzones[i].style.display = 'none'; }
}
- });
+ });
qq.attach(document, 'drop', function(e){
if (self._options.hideShowDropArea) {
for (i=0; i < dropzones.length; i++){ dropzones[i].style.display = 'none'; }
}
e.preventDefault();
- });
+ });
},
_onSubmit: function(id, fileName){
qq.FileUploaderBasic.prototype._onSubmit.apply(this, arguments);
- this._addToList(id, fileName);
+ this._addToList(id, fileName);
},
// Update the progress bar & percentage as the file is uploaded
_onProgress: function(id, fileName, loaded, total){
@@ -701,44 +701,44 @@ qq.extend(qq.FileUploader.prototype, {
var item = this._getItemByFileId(id);
var size = this._find(item, 'size');
size.style.display = 'inline';
-
+
var text;
var percent = Math.round(loaded / total * 100);
if (loaded != total) {
// If still uploading, display percentage
- text = percent + '% from ' + this._formatSize(total);
+ text = percent + '% from ' + this._formatSize(total);
} else {
// If complete, just display final size
text = this._formatSize(total);
- }
-
+ }
+
// Update progress bar <span> tag
this._find(item, 'progressBar').style.width = percent + '%';
-
- qq.setText(size, text);
+
+ qq.setText(size, text);
},
_onComplete: function(id, fileName, result){
qq.FileUploaderBasic.prototype._onComplete.apply(this, arguments);
// mark completed
- var item = this._getItemByFileId(id);
+ var item = this._getItemByFileId(id);
qq.remove(this._find(item, 'cancel'));
qq.remove(this._find(item, 'spinner'));
-
+
if (result.success){
- qq.addClass(item, this._classes.success);
+ qq.addClass(item, this._classes.success);
} else {
qq.addClass(item, this._classes.fail);
- }
+ }
},
_addToList: function(id, fileName){
- var item = qq.toElement(this._options.fileTemplate);
+ var item = qq.toElement(this._options.fileTemplate);
item.qqFileId = id;
- var fileElement = this._find(item, 'file');
+ var fileElement = this._find(item, 'file');
qq.setText(fileElement, this._formatFileName(fileName));
- this._find(item, 'size').style.display = 'none';
+ this._find(item, 'size').style.display = 'none';
if (!this._options.multiple) this._clearList();
this._listElement.appendChild(item);
},
@@ -746,53 +746,53 @@ qq.extend(qq.FileUploader.prototype, {
this._listElement.innerHTML = '';
},
_getItemByFileId: function(id){
- var item = this._listElement.firstChild;
-
+ var item = this._listElement.firstChild;
+
// there can't be txt nodes in dynamically created list
// and we can use nextSibling
- while (item){
- if (item.qqFileId == id) return item;
+ while (item){
+ if (item.qqFileId == id) return item;
item = item.nextSibling;
- }
+ }
},
/**
- * delegate click event for cancel link
+ * delegate click event for cancel link
**/
_bindCancelEvent: function(){
var self = this,
- list = this._listElement;
-
+ list = this._listElement;
+
this._attach(list, 'click', function(e){
e = e || window.event;
var target = e.target || e.srcElement;
-
- if (qq.hasClass(target, self._classes.cancel)){
+
+ if (qq.hasClass(target, self._classes.cancel)){
qq.preventDefault(e);
-
+
var item = target.parentNode;
self._handler.cancel(item.qqFileId);
qq.remove(item);
}
});
- }
+ }
});
-
+
qq.UploadDropZone = function(o){
this._options = {
- element: null,
+ element: null,
onEnter: function(e){},
- onLeave: function(e){},
- // is not fired when leaving element by hovering descendants
- onLeaveNotDescendants: function(e){},
- onDrop: function(e){}
+ onLeave: function(e){},
+ // is not fired when leaving element by hovering descendants
+ onLeaveNotDescendants: function(e){},
+ onDrop: function(e){}
};
qq.extend(this._options, o);
qq.extend(this, qq.DisposeSupport);
this._element = this._options.element;
-
+
this._disableDropOutside();
- this._attachEvents();
+ this._attachEvents();
};
qq.UploadDropZone.prototype = {
@@ -812,92 +812,92 @@ qq.UploadDropZone.prototype = {
qq.attach(document, 'dragover', function(e){
if (e.dataTransfer){
e.dataTransfer.dropEffect = 'none';
- e.preventDefault();
+ e.preventDefault();
}
});
}
- qq.UploadDropZone.dropOutsideDisabled = true;
- }
+ qq.UploadDropZone.dropOutsideDisabled = true;
+ }
},
_attachEvents: function(){
- var self = this;
-
+ var self = this;
+
self._attach(self._element, 'dragover', function(e){
if (!self._isValidFileDrag(e)) return;
-
+
var effect = qq.ie() ? null : e.dataTransfer.effectAllowed;
if (effect == 'move' || effect == 'linkMove'){
- e.dataTransfer.dropEffect = 'move'; // for FF (only move allowed)
- } else {
+ e.dataTransfer.dropEffect = 'move'; // for FF (only move allowed)
+ } else {
e.dataTransfer.dropEffect = 'copy'; // for Chrome
}
-
+
e.stopPropagation();
- e.preventDefault();
+ e.preventDefault();
});
self._attach(self._element, 'dragenter', function(e){
if (!self._isValidFileDrag(e)) return;
-
+
self._options.onEnter(e);
});
self._attach(self._element, 'dragleave', function(e){
if (!self._isValidFileDrag(e)) return;
-
+
self._options.onLeave(e);
-
- var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
+
+ var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
// do not fire when moving a mouse over a descendant
if (qq.contains(this, relatedTarget)) return;
-
- self._options.onLeaveNotDescendants(e);
+
+ self._options.onLeaveNotDescendants(e);
});
self._attach(self._element, 'drop', function(e){
if (!self._isValidFileDrag(e)) return;
-
+
e.preventDefault();
self._options.onDrop(e);
- });
+ });
},
_isValidFileDrag: function(e){
// e.dataTransfer currently causing IE errors
// IE9 does NOT support file API, so drag-and-drop is not possible
// IE10 should work, but currently has not been tested - any volunteers?
if (qq.ie()) return false;
-
+
var dt = e.dataTransfer,
- // do not check dt.types.contains in webkit, because it crashes safari 4
+ // do not check dt.types.contains in webkit, because it crashes safari 4
isSafari = qq.safari();
-
+
// dt.effectAllowed is none in Safari 5
- // dt.types.contains check is for firefox
- return dt && dt.effectAllowed != 'none' &&
+ // dt.types.contains check is for firefox
+ return dt && dt.effectAllowed != 'none' &&
(dt.files || (!isSafari && dt.types.contains && dt.types.contains('Files')));
- }
-};
+ }
+};
qq.UploadButton = function(o){
this._options = {
- element: null,
- // if set to true adds multiple attribute to file input
+ element: null,
+ // if set to true adds multiple attribute to file input
multiple: false,
acceptFiles: null,
// name attribute of file input
name: 'file',
onChange: function(input){},
hoverClass: 'qq-upload-button-hover',
- focusClass: 'qq-upload-button-focus'
+ focusClass: 'qq-upload-button-focus'
};
-
+
qq.extend(this._options, o);
qq.extend(this, qq.DisposeSupport);
this._element = this._options.element;
-
+
// make button suitable container for input
qq.css(this._element, {
position: 'relative',
@@ -905,37 +905,37 @@ qq.UploadButton = function(o){
// Make sure browse button is in the right side
// in Internet Explorer
direction: 'ltr'
- });
-
+ });
+
this._input = this._createInput();
};
qq.UploadButton.prototype = {
- /* returns file input element */
+ /* returns file input element */
getInput: function(){
return this._input;
},
/* cleans/recreates the file input */
reset: function(){
if (this._input.parentNode){
- qq.remove(this._input);
- }
-
+ qq.remove(this._input);
+ }
+
qq.removeClass(this._element, this._options.focusClass);
this._input = this._createInput();
- },
- _createInput: function(){
+ },
+ _createInput: function(){
var input = document.createElement("input");
-
+
if (this._options.multiple){
input.setAttribute("multiple", "multiple");
}
-
+
if (this._options.acceptFiles) input.setAttribute("accept", this._options.acceptFiles);
-
+
input.setAttribute("type", "file");
input.setAttribute("name", this._options.name);
-
+
qq.css(input, {
position: 'absolute',
// in Opera only 'browse' button
@@ -951,7 +951,7 @@ qq.UploadButton.prototype = {
cursor: 'pointer',
opacity: 0
});
-
+
this._element.appendChild(input);
var self = this;
@@ -979,8 +979,8 @@ qq.UploadButton.prototype = {
input.setAttribute('tabIndex', "-1");
}
- return input;
- }
+ return input;
+ }
};
/**
@@ -991,27 +991,27 @@ qq.UploadHandlerAbstract = function(o){
this._options = {
debug: false,
action: '/upload.php',
- // maximum number of concurrent uploads
+ // maximum number of concurrent uploads
maxConnections: 999,
onProgress: function(id, fileName, loaded, total){},
onComplete: function(id, fileName, response){},
onCancel: function(id, fileName){},
onUpload: function(id, fileName, xhr){}
};
- qq.extend(this._options, o);
-
+ qq.extend(this._options, o);
+
this._queue = [];
// params for files in queue
this._params = [];
};
qq.UploadHandlerAbstract.prototype = {
log: function(str){
- if (this._options.debug && window.console) console.log('[uploader] ' + str);
+ if (this._options.debug && window.console) console.log('[uploader] ' + str);
},
/**
* Adds file or file input to the queue
* @returns id
- **/
+ **/
add: function(file){},
/**
* Sends the file identified by id and additional query params to the server
@@ -1019,12 +1019,12 @@ qq.UploadHandlerAbstract.prototype = {
upload: function(id, params){
var len = this._queue.push(id);
- var copy = {};
+ var copy = {};
qq.extend(copy, params);
- this._params[id] = copy;
-
+ this._params[id] = copy;
+
// if too many active uploads, wait...
- if (len <= this._options.maxConnections){
+ if (len <= this._options.maxConnections){
this._upload(id, this._params[id]);
}
},
@@ -1050,7 +1050,7 @@ qq.UploadHandlerAbstract.prototype = {
getName: function(id){},
/**
* Returns size of the file identified by id
- */
+ */
getSize: function(id){},
/**
* Returns id of files being uploaded or
@@ -1066,21 +1066,21 @@ qq.UploadHandlerAbstract.prototype = {
/**
* Actual cancel method
*/
- _cancel: function(id){},
+ _cancel: function(id){},
/**
* Removes element from queue, starts upload of next
*/
_dequeue: function(id){
var i = qq.indexOf(this._queue, id);
this._queue.splice(i, 1);
-
+
var max = this._options.maxConnections;
-
+
if (this._queue.length >= max && i < max){
var nextId = this._queue[max-1];
this._upload(nextId, this._params[nextId]);
}
- }
+ }
};
/**
@@ -1089,7 +1089,7 @@ qq.UploadHandlerAbstract.prototype = {
*/
qq.UploadHandlerForm = function(o){
qq.UploadHandlerAbstract.apply(this, arguments);
-
+
this._inputs = {};
};
// @inherits qq.UploadHandlerAbstract
@@ -1098,25 +1098,25 @@ qq.extend(qq.UploadHandlerForm.prototype, qq.UploadHandlerAbstract.prototype);
qq.extend(qq.UploadHandlerForm.prototype, {
add: function(fileInput){
fileInput.setAttribute('name', this._options.inputName);
- var id = 'qq-upload-handler-iframe' + qq.getUniqueId();
-
+ var id = 'qq-upload-handler-iframe' + qq.getUniqueId();
+
this._inputs[id] = fileInput;
-
+
// remove file input from DOM
if (fileInput.parentNode){
qq.remove(fileInput);
}
-
+
return id;
},
getName: function(id){
// get input value and remove path to normalize
return this._inputs[id].value.replace(/.*(\/|\\)/, "");
- },
+ },
_cancel: function(id){
this._options.onCancel(id, this.getName(id));
-
- delete this._inputs[id];
+
+ delete this._inputs[id];
var iframe = document.getElementById(id);
if (iframe){
@@ -1127,30 +1127,30 @@ qq.extend(qq.UploadHandlerForm.prototype, {
qq.remove(iframe);
}
- },
+ },
_upload: function(id, params){
- this._options.onUpload(id, this.getName(id), false);
+ this._options.onUpload(id, this.getName(id), false);
var input = this._inputs[id];
-
+
if (!input){
throw new Error('file with passed id was not added, or already uploaded or cancelled');
- }
+ }
var fileName = this.getName(id);
-
+
var iframe = this._createIframe(id);
var form = this._createForm(iframe, params);
form.appendChild(input);
var self = this;
- this._attachLoadEvent(iframe, function(){
+ this._attachLoadEvent(iframe, function(){
self.log('iframe loaded');
-
+
var response = self._getIframeContentJSON(iframe);
self._options.onComplete(id, fileName, response);
self._dequeue(id);
-
+
delete self._inputs[id];
// timeout added to fix busy state in FF3.6
setTimeout(function(){
@@ -1159,11 +1159,11 @@ qq.extend(qq.UploadHandlerForm.prototype, {
}, 1);
});
- form.submit();
- qq.remove(form);
-
+ form.submit();
+ qq.remove(form);
+
return id;
- },
+ },
_attachLoadEvent: function(iframe, callback){
this._detach_event = qq.attach(iframe, 'load', function(){
// when we remove iframe from dom
@@ -1207,7 +1207,7 @@ qq.extend(qq.UploadHandlerForm.prototype, {
response = eval("(" + innerHTML + ")");
} catch(err){
response = {};
- }
+ }
return response;
},
@@ -1262,16 +1262,16 @@ qq.UploadHandlerXhr = function(o){
this._files = [];
this._xhrs = [];
-
- // current loaded size in bytes for each file
+
+ // current loaded size in bytes for each file
this._loaded = [];
};
// static method
qq.UploadHandlerXhr.isSupported = function(){
var input = document.createElement('input');
- input.type = 'file';
-
+ input.type = 'file';
+
return (
'multiple' in input &&
typeof File != "undefined" &&
@@ -1286,15 +1286,15 @@ qq.extend(qq.UploadHandlerXhr.prototype, {
/**
* Adds file to the queue
* Returns id to use with upload, cancel
- **/
+ **/
add: function(file){
if (!(file instanceof File)){
throw new Error('Passed obj in not a File (in qq.UploadHandlerXhr)');
}
-
- return this._files.push(file) - 1;
+
+ return this._files.push(file) - 1;
},
- getName: function(id){
+ getName: function(id){
var file = this._files[id];
// fix missing name in Safari 4
//NOTE: fixed missing name firefox 11.0a2 file.fileName is actually undefined
@@ -1303,29 +1303,29 @@ qq.extend(qq.UploadHandlerXhr.prototype, {
getSize: function(id){
var file = this._files[id];
return file.fileSize != null ? file.fileSize : file.size;
- },
+ },
/**
- * Returns uploaded bytes for file identified by id
- */
+ * Returns uploaded bytes for file identified by id
+ */
getLoaded: function(id){
- return this._loaded[id] || 0;
+ return this._loaded[id] || 0;
},
/**
* Sends the file identified by id and additional query params to the server
* @param {Object} params name-value string pairs
- */
+ */
_upload: function(id, params){
this._options.onUpload(id, this.getName(id), true);
-
+
var file = this._files[id],
name = this.getName(id),
size = this.getSize(id);
-
+
this._loaded[id] = 0;
-
+
var xhr = this._xhrs[id] = new XMLHttpRequest();
var self = this;
-
+
xhr.upload.onprogress = function(e){
if (e.lengthComputable){
self._loaded[id] = e.loaded;
@@ -1333,9 +1333,9 @@ qq.extend(qq.UploadHandlerXhr.prototype, {
}
};
- xhr.onreadystatechange = function(){
+ xhr.onreadystatechange = function(){
if (xhr.readyState == 4){
- self._onComplete(id, xhr);
+ self._onComplete(id, xhr);
}
};
@@ -1349,7 +1349,7 @@ qq.extend(qq.UploadHandlerXhr.prototype, {
xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
if (this._options.encoding == 'multipart') {
var formData = new FormData();
- formData.append(name, file);
+ formData.append(this._options.inputName, file);
file = formData;
} else {
xhr.setRequestHeader("Content-Type", "application/octet-stream");
@@ -1364,43 +1364,43 @@ qq.extend(qq.UploadHandlerXhr.prototype, {
_onComplete: function(id, xhr){
// the request was aborted/cancelled
if (!this._files[id]) return;
-
+
var name = this.getName(id);
var size = this.getSize(id);
-
+
this._options.onProgress(id, name, size, size);
-
+
if (xhr.status == 200){
this.log("xhr - server response received");
this.log("responseText = " + xhr.responseText);
-
+
var response;
-
+
try {
response = eval("(" + xhr.responseText + ")");
} catch(err){
response = {};
}
-
+
this._options.onComplete(id, name, response);
-
+
} else {
this._options.onError(id, name, xhr);
this._options.onComplete(id, name, {});
}
-
+
this._files[id] = null;
- this._xhrs[id] = null;
- this._dequeue(id);
+ this._xhrs[id] = null;
+ this._dequeue(id);
},
_cancel: function(id){
this._options.onCancel(id, this.getName(id));
-
+
this._files[id] = null;
-
+
if (this._xhrs[id]){
this._xhrs[id].abort();
- this._xhrs[id] = null;
+ this._xhrs[id] = null;
}
}
});
Something went wrong with that request. Please try again.