Skip to content

Instantly share code, notes, and snippets.

@ajayvarghese
Last active January 14, 2019 06:05
Show Gist options
  • Save ajayvarghese/d5ed9992c6f3b82489327f86ee21c45b to your computer and use it in GitHub Desktop.
Save ajayvarghese/d5ed9992c6f3b82489327f86ee21c45b to your computer and use it in GitHub Desktop.
export async function uploadFile(url, body, uploadActions) {
const formData = new FormData();
formData.append('dataset', body[0]);
const {
onUploadStart, onUploadProgress, onUploadSuccess,
onUploadError, onUploadAbort, onUploadEnd,
} = uploadActions;
let promise,
xhr;
promise = new Promise(((resolve) => {
xhr = new XMLHttpRequest();
if (xhr.upload) {
// Fetch start event listener - when upload starts
xhr.upload.addEventListener('loadstart', () => {
if (onUploadStart) {
onUploadStart();
}
});
// Progress event listener
if (onUploadProgress) {
xhr.upload.addEventListener('progress', (event) => {
if (event.lengthComputable) {
const uploadPercentage = (event.loaded / event.total) * 100;
onUploadProgress(Math.floor(uploadPercentage));
}
});
}
// Successful upload event listener - invoked once the upload is completed successfully.
xhr.addEventListener('load', () => {
try {
const response = JSON.parse(xhr.response);
// if (response && [200, 201].includes(xhr.status)) {
if (response && response.code !== 500) {
const result = response;
if (onUploadSuccess) {
onUploadSuccess(result);
}
resolve(result);
} else if (response) {
handleUploadError({ errorMessage: response.result || xhr.statusText, onUploadError });
}
} catch (e) {
console.error(e);
handleUploadError({
errorMessage: xhr.statusText || 'error in upload',
onUploadError,
});
}
});
// Abort event listener - upload abort by user
xhr.addEventListener('abort', () => {
if (onUploadAbort) {
onUploadAbort();
}
console.log('Abort');
});
// Error event listener - end of upload due to error
xhr.addEventListener('error', () => {
handleUploadError({
errorMessage: xhr.statusText,
onUploadError,
});
});
// Upload completion listener - Invoked on either success/error/abort
xhr.addEventListener('loadend', () => {
if (onUploadEnd) {
onUploadEnd();
}
});
xhr.open('POST', url);
xhr.send(formData);
}
}));
promise[CANCEL] = () => xhr.abort();
return promise;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment