Added upload function with PromiseProgress support
Some checks failed
Build / Build NPM Project (push) Failing after 29s
Build / Tag Version (push) Has been skipped

This commit is contained in:
Zakary Timson 2024-07-18 23:59:54 -04:00
parent 2a878b7962
commit 0693397164
2 changed files with 27 additions and 1 deletions

View File

@ -3,6 +3,7 @@ export * from './aset';
export * from './download';
export * from './emitter';
export * from './errors';
export * from './http.ts';
export * from './logger';
export * from './math';
export * from './misc';
@ -10,4 +11,4 @@ export * from './objects';
export * from './promise-progress';
export * from './string';
export * from './time';
export * from './http.ts';
export * from './upload.ts';

25
src/upload.ts Normal file
View File

@ -0,0 +1,25 @@
import {PromiseProgress} from './promise-progress.ts';
export type UploadOptions = {
url: string;
file: File;
headers?: {[key: string]: string};
withCredentials?: boolean;
}
export function uploadWithProgress(options: UploadOptions) {
return new PromiseProgress((res, rej, prog) => {
const xhr = new XMLHttpRequest();
const formData = new FormData();
formData.append('file', options.file);
xhr.withCredentials = !!options.withCredentials
Object.entries(options.headers || {}).forEach(([key, value]) => xhr.setRequestHeader(key, value));
xhr.upload.addEventListener('progress', (event) => event.lengthComputable ? prog(event.loaded / event.total) : null);
xhr.upload.addEventListener('load', (resp) => res(resp));
xhr.upload.addEventListener('error', (err) => rej(err));
xhr.open('POST', options.url);
xhr.send(formData);
});
}