Skip to content

Instantly share code, notes, and snippets.

@ti-ka
Last active February 9, 2016 03:37
Show Gist options
  • Save ti-ka/441b06d47ce457e6dc57 to your computer and use it in GitHub Desktop.
Save ti-ka/441b06d47ce457e6dc57 to your computer and use it in GitHub Desktop.
"use strict";
var ImageUploader = {
uploadURL : 'admin/inventory/uploadImage',
inputObject : document.getElementById('item-image-upload'),
uploadEntityName : "photos[]",
callback : function(response){
console.log(response);
},
upload : function(){
var formData = this.prepareFormData();
this.initiateAjaxUpload(formData);
},
initiateAjaxUpload : function(formData){
var uploader = this;
var xhr = new XMLHttpRequest();
xhr.open('POST', uploader.uploadURL , true);
xhr.onload = function (response) {
if (xhr.status === 200) {
uploader.callback(response.target.response);
} else {
alert('An error occurred in uploading files.');
}
};
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.responseType = "json";
xhr.send(formData);
},
getFiles : function(){
if(this.inputObject && this.inputObject.files){
return this.inputObject.files;
}
return [];
},
prepareFormData : function(){
var files = this.getFiles();
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image.*')) {
continue;
}
formData.append(this.uploadEntityName, file);
}
formData.append("Apple", 1);
return formData;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment