Skip to content

Instantly share code, notes, and snippets.

@qetr1ck-op
Last active December 5, 2015 17:35
Show Gist options
  • Save qetr1ck-op/944b71874078f509ec5b to your computer and use it in GitHub Desktop.
Save qetr1ck-op/944b71874078f509ec5b to your computer and use it in GitHub Desktop.
var module = angular.module('uploader', []);
module.service('uploader', ['$q', function($q) {
function readyStateChange(deferred, xhr) {
if(xhr.readyState == 4) {
if(xhr.status == 200) {
deferred.resolve(JSON.parse(xhr.responseText));
}
else {
deferred.reject('HTTP status ' + xhr.status);
}
}
}
function onProgress(deferred, xhr, ev) {
if (ev.lengthComputable) {
deferred.notify({ loaded: ev.loaded, total: ev.total });
}
}
return {
send: function(url, data) {
var fd = new FormData();
for(var k in data) {
fd.append(k, data[k]);
}
var d = $q.defer();
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onreadystatechange = readyStateChange.bind({}, d, xhr);
xhr.upload.onprogress = onProgress.bind({}, d, xhr);
xhr.send(fd);
return d.promise;
},
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment