我有要附加的文档列表,每个文档最多可以包含20 MB数据,并且用户可以附加任意数量的文件,因此,每个rest调用我都发送一个文件。
保存所有文档后,将用户重定向到showStudent页面。
这是我的代码,但是问题是,它仅适用于单个文件。我要等到所有文件都保存完。
uploadAttachments(student: Student, documents: Document[]): Observable<Response> {
let status;
let user = JSON.parse(localStorage.getItem('user'));
let userId = user.id;
let headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('token')
});
let url = environment.userResourceEndpoint + userId + "/documents/attach";
let body;
let document = documents[index];
body = new FormData();
console.log("###############Uploading document:" + document.title);
let fileUpload: File = document.file;
body.append('attachTo', 'student');
body.append('attachToId', student.id);
body.append('title', document.title);
body.append('file', fileUpload, fileUpload.name);
return this.http.post(url, body, headers)
.map((res: Response) => {
res.json() as Student;
if (index < documents.length - 1) {
index = index + 1;
this.uploadAttachments(student, documents);
}
})
.catch((error: any) => {
if (error.status === 0) {
console.log(" Server is down???");
}
return Observable.throw(error);
});
}
答案 0 :(得分:1)
我已经通过@SourangshuSengupta发送给我的链接并实现了该解决方案,并且该解决方案有效。
这是完整的方法代码以供参考:
uploadAttachments(user: User, documents: Document[]): Observable<any> {
let status;
let observableObj = new Observable<Response>();
let user = JSON.parse(localStorage.getItem('user'));
let userId = user.id;
let headers = new Headers({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('token')
});
let url = environment.userResourceEndpoint + userId + "/documents/attach";
let body;
let observables = [];
documents.forEach(item => {
body = new FormData();
let fileUpload: File = item.file;
body.append('attachTo', 'user');
body.append('attachToId', user.id);
body.append('title', item.title);
body.append('file', fileUpload, fileUpload.name);
observables.push(this.http.post(url, body, headers).map(res => res.json()));
});
return Observable.forkJoin(observables)
.map(res => res.length)
.catch((error: any) => {
if (error.status === 0) {
console.log(" Server is down???");
}
return Observable.throw(error);
});
}