export class UploadFile { // tslint:disable-next-line:max-line-length constructor(public file: File, public parameters: {}, public url, private onCompleted?: (data: T) => void, private onProgress?: (evt: Event) => void, private onError?: (error: any) => void) { } startUpload(): UploadFile { this.uploadFile(this.file); return this; } private uploadFile(file: File) { const xhr: XMLHttpRequest = new XMLHttpRequest(); const formData: FormData = new FormData(); xhr.open('POST', this.url, true); xhr.upload.onprogress = this.onProgressHandler; xhr.upload.onload = this.onProgressCompleted; xhr.onload = this.onLoadCompleted; for (const key in this.parameters) { if (this.parameters.hasOwnProperty(key)) { formData.append(key, this.parameters[key]); } } formData.append('file', file); xhr.send(formData); } private onProgressHandler = (evt: Event) => { if (this.onProgress != null) { this.onProgress(evt); } } private onProgressCompleted = (evt: Event) => { if (this.onProgress != null) { this.onProgress(evt); } } private onLoadCompleted = (evt: Event) => { const xhr: any = evt.srcElement; try { const result: T = JSON.parse(xhr.responseText); if (this.onCompleted != null) { this.onCompleted(result); } } catch (e) { if (this.onError != null) { this.onError(e); } } } }