原因:forEach 只支持同步,不支持异步
解决办法:
用for of循环
(async()=>{
let index = 0 ;
for(let val of this.files){
formData = new FormData();
formData.append("image",val);
formData.append("id",this.id);
formData.append('content',this.fileList[index]);
index++;
formData.append('title',this.title);
formData.append('type',this.curType);
// 文件上传
result = await new Promise(resolve=>{
this.$axios({
method: "POST",
url: 'http://localhost:8080/uploadFile',
data: formData
}).then((res) => {
console.log(res);
resolve(res.data.data);
}).catch((e)=>{
alert('err');
})
})
}
if(result=='success'){
this.$router.push('/home');
}else{
alert('err')
}
})()
使用for...of循环实现异步文件上传

本文介绍了一种使用for...of循环替代forEach进行异步文件上传的方法,解决了forEach不支持异步的问题。通过创建FormData实例,将文件和其他参数附加到表单数据中,并使用axios发起POST请求,实现了文件的异步上传。
966

被折叠的 条评论
为什么被折叠?



