我正在尝试将文件数组保存到Spring Boot服务器。一次保存一个文件。我用for循环迭代文件数组,并请求保存每个文件。在这里,我希望仅在获得第一个文件的响应后才能进行下一次调用。我已经尝试了下面给出的代码,但无法实现。
public uploadNewsFiles() {
for (let index = 0; index < this.files.length; index++) {
debugger;
var body = new FormData();
// alert(this.files[index].name);
body.append('file', this.files[index]);
this.uploading.push(true);
this.uload(body,this.newsId,this.getFileDescriptionFormGroup(index)
.controls['des'].value,index).then((status:any)=>
{
if (status.status === 'success') {
// alert('success');
body.delete('file');
this.uploading[index] = false;
this.uploadingStatus.push(true);
} else {
body.delete('file');
this.uploading[index] = false;
this.uploadingStatus.push(false);
}
},(err)=>alert('failed'))
}
// body.append('newsId',this.newsId);
}
async uload(body,newsId,desc,index) {
return await this.service.saveFiles(body, newsId,desc).toPromise();
}
public saveFiles(body,newsId,des) {
return this.http.post(this.url + '/saveFiles?
newsId='+newsId+'&fileDescription='+des,body);
}
答案 0 :(得分:0)
您可以使用async
await
。
async uploadNewsFiles() {
for (let index = 0; index < this.files.length; index++) {
var body = new FormData();
body.append('file', this.files[index]);
this.uploading.push(true);
await this.uload(body,this.newsId,this.getFileDescriptionFormGroup(index)
.controls['des'].value,index).then((status:any)=>
{
if (status.status === 'success') {
body.delete('file');
this.uploading[index] = false;
this.uploadingStatus.push(true);
// here we are calling the
} else {
body.delete('file');
this.uploading[index] = false;
this.uploadingStatus.push(false);
}
},(err)=>alert('failed'))
}
}
uload(body,newsId,desc,index) {
return new Promise((resolve, reject) => {
this.service.saveFiles(body, newsId,desc).toPromise().then(resp => {
resolve(resp); // here we are resolving our promise
});
});
}
服务
public saveFiles(body,newsId,des) {
return this.http.post(this.url + '/saveFiles?
newsId='+newsId+'&fileDescription='+des,body);
}
希望它能对您有所帮助。
答案 1 :(得分:0)
由于您使用的是Angular,因此我们可以利用rxjs
库,而不是使用toPromise
并从http调用中链接可观察对象,例如:
function modUploadFiles() {
this.files
.map((file, index) => {
const body = new FormData();
body.append("file", file);
const newsId = this.newsId;
const desc = this.getFileDescriptionFormGroup(index).controls["des"]
.value;
return this.service.saveFiles(body, newsId, desc).finally(status => {
body.delete("file");
this.uploading[index] = false;
this.uploadingStatus.push(status.status === "success");
})
})
.reduce((acc, next) => acc.flatMap(() => next))
.subscribe(result => {/*Do something*/});
}
您可以在以下问题中查看更多信息: