function fileUpload(options) {
var opts = options || {};
var func =
function() {};
this.fileInput = opts.fileInput ||
null;
this.url = opts.url ||
'';
this.fileList = [];
this.onFilter = opts.onFilter ||
function(f) {
return f;};
this.onSelect = opts.onSelect || func;
this.onProgress = opts.onProgress || func;
this.onSuccess = opts.onSuccess || func;
this.onFailure = opts.onFailure || func;
this.onComplete = opts.onComplete || func;
this.init();
}
fileUpload.prototype = {
dealFiles:
function(e) {
var files = e.target.files || e.dataTransfer.files;
this.fileList =
this.onFilter(files);
for(
var i =
0, file; file =
this.fileList[i]; i++){
file.index = i;
}
this.onSelect(
this.fileList);
return
this;
},
removeFile:
function(fileDelete) {
var arrFile = [];
for(
var i =
0, file; file =
this.fileList[i]; i++){
if (file != fileDelete) {
arrFile.push(file);
}
}
this.fileList = arrFile;
return
this;
},
removeAll:
function() {
this.fileList = [];
return
this;
},
uploadFile:
function() {
var me =
this;
for(
var i =
0, file; file =
this.fileList[i]; i++){
(
function(file) {
var formData =
new FormData();
var xhr =
new XMLHttpRequest();
if (xhr.upload) {
xhr.upload.addEventListener(
"progress",
function(e) {
me.onProgress(file, e.loaded, e.total);
},
false);
xhr.onreadystatechange =
function(e) {
if (xhr.readyState ==
4) {
if (xhr.status ==
200) {
me.onSuccess(file, xhr.responseText);
me.removeFile(file);
if (!me.fileList.length) {
me.onComplete();
}
}
else {
me.onFailure(file, xhr.responseText);
}
}
};
formData.append(
'file', file);
xhr.open(
"POST", me.url,
true);
xhr.send(formData);
}
})(file);
}
},
init:
function() {
var me =
this;
if (me.fileInput) {
me.fileInput.addEventListener(
"change",
function(e) { me.dealFiles(e); },
false);
}
}
};