javascript - 如何在最终表单提交之前异步/等待多次上传?
问题描述
我试图允许用户上传多个文件。选择的每个文件都会触发一个axios.post()
请求......因此,如果用户选择三个文件,那么将向axios.post()
服务器发出三个单独的请求以上传文件。
表单中还有其他字段,例如当用户单击表单提交按钮Name
时Description
将提交哪些字段。但是,我希望表单提交等到所有文件都先上传。
为简洁起见,这是代码的缩短版本:
<form @submit.prevent="sendForm" enctype="multipart/form-data">
<input multiple ref="PostFiles" name="PostFiles" type="file" @change="selectFile">
... // other fields here
<button type="submit" name="Send" value="Send"></button>
</form>
methods: {
selectFile() {
const this.Form.UploadFiles = this.$refs.PostFiles.files; // all files selected by user to upload
Array.from(this.Form.UploadFiles).forEach(file => {
this.uploadFile(file) // each file gets sent to uploadFile() individually
});
},
async uploadFile(File) {
const FormFile = new FormData();
FormFile.append("PostFile", File);
await this.$axios.post('/api', FormFile).then(response => {
console.log("Successfully uploaded")
}).catch(err => {
console.log(err.response.data.error)
})
return true;
},
async sendForm() {
const FormBody = new FormData();
FormBody.append("Name", this.Form.Name);
FormBody.append("Description", this.Form.Description);
// Here I need to wait for all files to upload first!
await this.uploadFile();
// If all files uploaded then post the form
await this.$axios.post('/api', FormBody)
}
因为在每次单独上传后uploadFile()
返回,所以将在第一个文件上传后提交。但我需要等到数组中的所有文件都上传完毕。我怎么能那样做?true
sendForm()
this.Form.UploadFiles
解决方案
您可以制作selectFiles
并async
使用 for 循环而不是forEach()
async selectFile() {
const this.Form.UploadFiles = this.$refs.PostFiles.files; // all files selected by user to upload
for (const eachFile of Array.from(this.Form.UploadFiles)) {
await this.uploadFile(eachFile); // each file gets sent to uploadFile() individually
}
}
async sendForm() {
const FormBody = new FormData();
FormBody.append("Name", this.Form.Name);
FormBody.append("Description", this.Form.Description);
// Here I need to wait for all files to upload first!
await this.selectFile(); //<--this is the change you need
// If all files uploaded then post the form
await this.$axios.post('/api', FormBody)
}
推荐阅读
- scala - 对两个列表进行元素总和的最快方法
- c# - 通过蓝牙流式传输音频
- rest - 用于获取 HDInsight 群集的性能指标的 REST API?
- purescript - 如何在 Purescript 中使用 mapWithIndex?
- java - 测试它说它终止的输出
- automation - 我们可以使用哪个自动化工具来自动化安全应用程序(我们不能在其中录制视频和屏幕截图?
- c - 这是 C 语言未定义的行为吗?clang 和 GCC 中的不同结果
- c# - 从方法外部获取到动作的路线
- python-2.7 - 为什么这个 if、elif 和 if 语句不适用于 raw_input
- java - JPA,Spring映射多个实体