Created
May 2, 2024 18:24
-
-
Save xettri/c2e8fae2bdfad3218ebfbbacec793f53 to your computer and use it in GitHub Desktop.
This file contains 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
export const uploadFile = ({ | |
api, | |
fileId, | |
payload, | |
onSuccess: _onSuccess, | |
onProgress: _onProgress, | |
onError: _onError, | |
onAbort: _onAbort, | |
abortMaker, | |
}) => { | |
const onProgress = (progress) => { | |
if (typeof _onProgress === 'function') { | |
_onProgress(progress, fileId); | |
} | |
}; | |
const onError = error => { | |
if (typeof _onError === 'function') { | |
_onError(error, fileId); | |
} | |
}; | |
const onAbort = error => { | |
if (typeof _onAbort === 'function') { | |
_onAbort(error, fileId); | |
} | |
}; | |
const onSuccess = data => { | |
if (typeof _onSuccess === 'function') { | |
_onSuccess(data, fileId); | |
} | |
}; | |
return new Promise(function (resolve, reject) { | |
const xhr = new XMLHttpRequest(); | |
// this will create abort util | |
if (typeof abortMaker === 'function') { | |
abortMaker(() => { | |
xhr.abort(); | |
}); | |
} | |
for (let header in api.headers) { | |
xhr.setRequestHeader(header, api.headers[header]); | |
} | |
xhr.onload = function onload() { | |
if (this.status >= 200 && this.status < 300) { | |
onSuccess(xhr.response); | |
resolve(xhr.response); | |
} else { | |
const err = { | |
status: xhr.status, | |
statusText: xhr.statusText, | |
}; | |
onError(err); | |
reject(err); | |
} | |
}; | |
xhr.upload.addEventListener('progress', function (e) { | |
/** | |
* The ProgressEvent.lengthComputable read-only property is a boolean flag indicating | |
* if the resource concerned by the ProgressEvent has a length that can be calculated | |
* see: https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent/lengthComputable | |
*/ | |
if (e.lengthComputable) { | |
const percentage = Math.round((e.loaded * 100) / e.total); | |
onProgress(percentage); | |
} | |
}); | |
xhr.onerror = function onerror() { | |
const err = { | |
status: xhr.status, | |
statusText: xhr.statusText, | |
}; | |
onError(err); | |
reject(err); | |
}; | |
xhr.onabort = function onabort() { | |
const err = { | |
status: xhr.status, | |
statusText: 'Aborted', | |
}; | |
onAbort(err); | |
reject(err); | |
}; | |
xhr.open(api.method || 'PUT', api.url); | |
xhr.send(payload); | |
}); | |
}; | |
export default uploadFile; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment