I want to implement post file and Json data in the same request .
below is the upload file code :
upload(url:string,file:File):Observable<{complate:number,progress?:number,data?:Object}>{
return Observable.create(observer => {
const formData:FormData = new FormData(),
xhr:XMLHttpRequest = new XMLHttpRequest();
formData.append('uploadfile', file);
formData.append("_csrf", this.tokenService.getCsrf());
xhr.open('POST',url, true);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next({complate:1,progress:100,data:JSON.parse(xhr.response)});
observer.complete();
} else {
observer.error(xhr.response);
}
}
};
xhr.upload.onprogress = (event) => {
observer.next({complate:0,progress:Math.round(event.loaded / event.total * 100)});
};
const headers=new Headers();
let token: string = localStorage.getItem('access-token');
xhr.setRequestHeader('Authorization', `Bearer ${token}`);
xhr.send(formData);
}).share();
How to integration with angular2 http.post(url, JSON.stringify(data)).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…