utils/src/upload.ts
ztimson 0985ff145e
All checks were successful
Build / Build NPM Project (push) Successful in 16s
Build / Tag Version (push) Successful in 4s
Build / Publish (push) Successful in 7s
Fixed file upload types
2024-04-24 07:06:17 -04:00

31 lines
890 B
TypeScript

import {TypedEmitter, TypedEvents} from './emitter';
export type UploadEvents = TypedEvents & {
complete: () => any;
failed: (err: Error) => any;
progress: (progress: number) => any;
}
export function uploadProgress(files : File | File[], url: string) {
const xhr = new XMLHttpRequest();
const progress = new TypedEmitter<UploadEvents>();
const formData = new FormData();
(Array.isArray(files) ? files : [files])
.forEach(f => formData.append('file', f));
xhr.upload.addEventListener("progress", (event) => {
if(event.lengthComputable) progress.emit('progress', event.loaded / event.total);
});
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if(xhr.status >= 200 && xhr.status < 300) progress.emit('complete');
else progress.emit('failed', new Error(xhr.responseText));
}
};
xhr.open("POST", url, true);
xhr.send(formData);
return progress;
}