vue项目实现多文件统一上次

226 阅读1分钟

需求就是让用户选择多个文件后只调用一次后台接口

html部分:

<el-upload
      action=""
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      ref="upload"
      multiple
      :auto-upload="false"
      :on-change="handleChange"
      accept=".txt"
      :before-upload="beforeAvatarUpload"
    >
   <div class="inputB_btn" style="background:#67C23A">选取文件</div>
       
 </el-upload>

js部分:

 handleChange(fileList) {
            this.fileName = fileList.name
            this.fileList.push(fileList)
            let arr = []
             this.fileList.forEach(file => {
                arr.push(file.name)
           })
           this.fileName = arr.join(',')
        
        },
 // 多文件上传
        submitFile() {
            const formData = new FormData()
            // 因为要传一个文件数组过去,所以要循环append
            this.fileList.forEach((file,i) => {
                formData.append(`file${i+1}`, file.raw)
            })
            var that = this;
                this.$axios({
                        'url':`${window.localStorage.getItem('webUrl')}/api/file/upload`,
                        // 'url': 'https://xxx.com/api/file/upload',
                        'data': formData,
                        'method': 'POST',
                        contentType: false,//这里不要落下
                        headers: {
                            'Content-Type': ' multipart/form-data',
                            'Authorization': `${this.token}`
                        },
                        processData: false //告诉jquery不要对form进行处理
                    })
                    .then(function (res) {
                        if (res.data.code == 10000) {
                            that.fileName_a = res.data.data[0].file_name
                            that.newFileName = res.data.data[0].new_file_name
                            that.showBtn = true
                            that.fileList = []
                            that.myFunction();
                        } else {
                            that.$message.error(res.data.message)
                        }
                        console.log(res)
                    })
                    .catch(function (err) {
                        console.log(err)
                    })
                
        },