Skip to content

Instantly share code, notes, and snippets.

@xettri
Created November 30, 2023 11:27
Show Gist options
  • Save xettri/db6e4c78895c72e90900e11bef125e52 to your computer and use it in GitHub Desktop.
Save xettri/db6e4c78895c72e90900e11bef125e52 to your computer and use it in GitHub Desktop.
/**
* Uploads a file using XMLHttpRequest with progress, error, and abort handling.
*
* @param {Object} options - The options for the file upload.
* @param {string} options.api - The API endpoint for the file upload.
* @param {File} options.file - The File object to be uploaded.
* @param {string} options.type - The MIME type of the file.
* @param {string} [options.method="PUT"] - The HTTP method for the request.
* @param {function} [options.onProgress] - A callback function to handle upload progress.
* @param {function} [options.onError] - A callback function to handle upload errors.
* @param {function} [options.onAbort] - A callback function to handle upload aborts.
*
* @returns {Promise} A Promise that resolves on successful upload or rejects on failure.
*/
export const uploadFile = ({
api,
file,
type,
method = "PUT",
onProgress,
onError,
onAbort,
}) => {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.open(method, api);
xhr.overrideMimeType(type);
xhr.upload.addEventListener("progress", function (e) {
onProgress((e.loaded / e.total) * 100);
});
xhr.onerror = function () {
if (typeof onError === "function") {
onError({
status: xhr.status,
statusText: xhr.statusText,
});
}
reject({
status: xhr.status,
statusText: xhr.statusText,
});
};
xhr.onabort = function () {
if (typeof onAbort === "function") {
onAbort();
}
reject({
status: xhr.status,
statusText: "Aborted",
});
};
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText,
});
}
};
xhr.send(file);
return xhr;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment