Last active
December 5, 2015 17:35
-
-
Save qetr1ck-op/944b71874078f509ec5b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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