Skip to content

Instantly share code, notes, and snippets.

@AndreasDickow
Created August 9, 2017 10:16
Show Gist options
  • Save AndreasDickow/8a8cb1f67dff7ed6cc8ad3188aca729c to your computer and use it in GitHub Desktop.
Save AndreasDickow/8a8cb1f67dff7ed6cc8ad3188aca729c to your computer and use it in GitHub Desktop.
Angular2 Image Upload to Django Rest Framework with Form Data
@Injectable()
export class UploadService {
/**
* @param Observable<number>
*/
private progress$: Observable<number>;
/**
* @type {number}
*/
private progress: number = 0;
private progressObserver: any;
constructor() {
this.progress$ = new Observable(observer => {
this.progressObserver = observer
});
}
/**
* @returns {Observable<number>}
*/
public getObserver(): Observable<number> {
return this.progress$;
}
/**
* Upload files through XMLHttpRequest
*
* @param url
* @param files
* @returns {Promise<T>}
*/
public upload(url: string, formdata: FormData,headers:string): Promise<any> {
return new Promise((resolve, reject) => {
let xhr: XMLHttpRequest = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.response);
resolve(JSON.parse(xhr.response));
} else {
console.log(xhr.response);
reject(xhr.response);
}
}
};
UploadService.setUploadUpdateInterval(500);
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('PATCH', url, true);
xhr.setRequestHeader("Authorization",headers);
xhr.send(formdata);
console.log("sent");
});
}
/**
* Set interval for frequency with which Observable inside Promise will share data with subscribers.
*
* @param interval
*/
private static setUploadUpdateInterval(interval: number): void {
setInterval(() => {
}, interval);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment