helpers/upload-files.js

62 lines
2.2 KiB
JavaScript
Raw Permalink Normal View History

2022-10-29 22:05:19 +02:00
export const upload = function(superClass) {
return class extends superClass {
/**
* Upload files to the backend
*
* @param {String} id An identifier send with the upload events to filter out the right upload if multiple onces are running.
* @param {Array} files List of files to upload
* @param {Object} opts Upload options
* @returns Promise
*/
2023-07-27 16:40:07 +02:00
uploadFiles(url, files, data = {}) {
2022-10-29 22:05:19 +02:00
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
const formData = new FormData();
2023-07-27 16:40:07 +02:00
for (const key in data) {
formData.append(key, data[key]);
2022-10-29 22:05:19 +02:00
}
request.open('POST', url, true);
request.addEventListener('readystatechange', () => {
if (request.readyState === 4) {
resolve(request);
}
});
2023-07-27 16:40:07 +02:00
request.addEventListener('loadstart', e => {
this.dispatchEvent(new CustomEvent('upload-started', { detail: e, bubbles: true, composed: true }));
});
request.addEventListener('progress', e => {
2022-10-29 22:05:19 +02:00
this.dispatchEvent(new CustomEvent('upload-progress', { detail: { percent: ((e.loaded / e.total) * 100).toFixed(2) }, bubbles: true, composed: true }));
});
2023-07-27 16:40:07 +02:00
request.addEventListener('error', e => {
this.dispatchEvent(new CustomEvent('upload-error', { detail: e, bubbles: true, composed: true }));
});
request.addEventListener('error', e => {
this.dispatchEvent(new CustomEvent('upload-error', { detail: e, bubbles: true, composed: true }));
});
2022-10-29 22:05:19 +02:00
request.addEventListener('load', () => {
this.dispatchEvent(new CustomEvent('upload-finished', { detail: null, bubbles: true, composed: true }));
});
2023-07-27 16:40:07 +02:00
request.addEventListener('abort', () => {
this.dispatchEvent(new CustomEvent('upload-aborted', { detail: null, bubbles: true, composed: true }));
});
2022-10-29 22:05:19 +02:00
for (let i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
2022-11-15 20:12:51 +01:00
document.dispatchEvent(new CustomEvent('before-request', { detail: request, bubbles: true, composed: true }));
2022-10-29 22:05:19 +02:00
request.send(formData);
});
}
};
};