Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save LarsKoelpin/ed52560d9c5601ef7ba7 to your computer and use it in GitHub Desktop.
export const UPLOAD_NONE = 'UPLOAD_NONE';
export const UPLOAD_STARTED = 'UPLOAD_STARTED';
export const UPLOAD_INVALID = 'UPLOAD_INVALID';
export const UPLOAD_SUCCESS = 'UPLOAD_SUCCESS';
export const UPLOAD_ERROR = 'UPLOAD_ERROR';
export function uploadFile(file) {
return (dispatch) => {
dispatch(uploadStart())
return uploadFile(file, ()=> {
console.log('finished');
return uploadSucceed();
},
()=> {
return uploadSucceed();
console.log('eror');
})
}
}
export function uploadStart() {
return {
type: UPLOAD_STARTED
}
}
export function uploadSucceed() {
return {
type: UPLOAD_STARTED
}
}
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