Send multi files in base64 to server
document.getElementById('upload-photo').addEventListener('change', function(e) {
new UploadPhoto({
el: e.target,
files: e.target.files,
clubID: 3
}).send();
});
;(function() {
this.UploadPhoto = function(param) {
this.param = param || {};
this.filesCount = 40;
this.messages = {
error: 'Max upload photos is ' + this.filesCount,
success: 'Photos is uploaded',
notUploaded: 'is not uploaded',
notValid: 'is not valid format'
};
}
/**
*
* private methods
*
*/
function readFile(file) {
var self = this;
var reader = new FileReader();
return new Promise(function(resolve, reject) {
if(/^image/.test(file.type)) {
reader.onload = function() {
if(reader.readyState === 2) {
resolve({
name: file.name,
data: reader.result
});
}
else {
reject(file.name + ' ' + self.messages.notUploaded)
}
}
reader.readAsDataURL(file);
}
else{
reject(file.name + ' ' + self.messages.notValid)
}
});
}
/**
*
* public methods
*
*/
UploadPhoto.prototype = {
getMessage: function(type) {
return {
type: type,
message: this.messages[type]
};
},
checkFilesCount: function() {
return this.param.files.length > this.filesCount ? this.getMessage('error') : this.getMessage('success');
},
send: function() {
var self = this;
var check = this.checkFilesCount();
var loaded = 0;
var imgContainer = document.querySelector('.photos');
if(check.type !== 'error') {
var promises = [];
// push promuses to array
for (var i = this.param.files.length - 1; i >= 0; i--) {
promises.push(readFile.call(this, this.param.files[i]));
}
// array of values from all promises and send files to server
Promise.all(promises)
.then(function(data) {
var ajax = new Ajax({
method: 'post',
url: '/admin/player.php?upload=1&gh_id=' + self.param.clubID,
type: 'json',
data: data
}).send();
})
.catch(function(error) {
toastr.error(error);
});
}
else {
toastr.error(check.message);
}
}
};
})();