Added upload function with PromiseProgress support
This commit is contained in:
parent
2a878b7962
commit
0693397164
@ -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
25
src/upload.ts
Normal 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);
|
||||
});
|
||||
}
|
Loading…
Reference in New Issue
Block a user