首页 > 解决方案 > 如何在最终表单提交之前异步/等待多次上传?

问题描述

我试图允许用户上传多个文件。选择的每个文件都会触发一个axios.post()请求......因此,如果用户选择三个文件,那么将向axios.post()服务器发出三个单独的请求以上传文件。

表单中还有其他字段,例如当用户单击表单提交按钮NameDescription将提交哪些字段。但是,我希望表单提交等到所有文件都先上传。

为简洁起见,这是代码的缩短版本:

<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()返回,所以将在第一个文件上传后提交。但我需要等到数组中的所有文件都上传完毕。我怎么能那样做?truesendForm()this.Form.UploadFiles

标签: javascriptvue.jsaxios

解决方案


您可以制作selectFilesasync使用 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)
  }

推荐阅读