Skip to content

Instantly share code, notes, and snippets.

@LarsKoelpin
Created March 15, 2016 22:00
Show Gist options
  • Select an option

  • Save LarsKoelpin/9136cb047aac4c22093a to your computer and use it in GitHub Desktop.

Select an option

Save LarsKoelpin/9136cb047aac4c22093a to your computer and use it in GitHub Desktop.
function uploadFile(file, finish = () =>{}, error = ()=>{}) {
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
var percentComplete = (e.loaded / e.total) * 100;
console.log('Uploaded ' + percentComplete + ' percentComplete');
};
xhr.onload = function() {
if (xhr.status == 200) {
console.log("SUC");
} else {
error()
}
};
xhr.onerror = function() {
error()
};
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE
&& xhr.status === 200) {
if(finish)
finish(xhr.responseText);
} else {
error()
}
};
xhr.open('PUT', '/upload', true);
if(file != null)
xhr.setRequestHeader('Content-Type', file.type);
xhr.send(file);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment