element ui 附件一次上传多个但只请求一次并直接与后端交互上传至系统

element ui 附件一次上传多个但只请求一次并直接与后端交互上传至系统

需求: 选择完文件直接上传系统,不再有多余按钮触发
实现: element ui upload组件的多附件上传是循环调用上传接口的,在每次on-change 改变后调用后端接口交互
问题: 调用后端接口多次,会导致后端接口并发报错。
解决办法: 想要把上传的多个附件一次性传给后端,只调用一次接口,但是不知道什么时候触发调用接口动作,所以就需要知道选择的文件数量,当选择的文件数量等于了上传的文件数量时就可以调用接口了,而且要自定义上传接口请求,不要循环调用,不然接口是异步请求的,还是不能知道什么时候全部调用完毕。
代码实现:

<el-upload
            class="upload-demo"
            :auto-upload="false"
            multiple
            action="#"
            :file-list="fileList"
            :on-change="handleChange"
            :show-file-list="false"
            :disabled="uploadLoading"
            style="width: 120px"
        >
            <el-button style="float: left" size="small" v-if="isShowUploadBtn" :loading="uploadLoading">
                <el-icon class="el-icon-paperclip">el-icon>
                <label class="table-head-button-lable">{{ btnMsg || t('上传附件') }}label>
            el-button>
        el-upload>
setup(props, { emit }) {
        let uploadLoading = ref(false);
        const addNum = ref(0);
        const num = ref([]);
        const handleChange = async (file) => {
            // 上传即提交,判断选取文件数量等于上传次数再提交,避免分开调用后端并发报错
            if (props.isUploadAndSubmit) {
                uploadLoading.value = true;
                var upload_img = document.getElementsByClassName('upload-demo');
                let uploadNum = 0;
                if (upload_img && upload_img.length > 0) {
                    var upload = upload_img[0].getElementsByTagName('input');
                    if (upload && upload.length > 0 && upload[0].files && upload[0].files.length > 0) {
                        uploadNum = upload[0].files.length;
                    }
                }
                addNum.value++;
                num.value.push(file);
                if (addNum.value == uploadNum) {
                    const formData = new FormData();
                    num.value
                        .filter((n) => !n.fileUrl)
                        .forEach(async (item) => {
                            formData.append('fileList', item.raw);
                        });

                    let res = await uploadFileList(formData);

                    if (res) {
                        res.forEach((r) => {
                            fileList.value.push(r);
                        });
                        emit('handleAdd', res);
                        addNum.value = 0;
                        num.value = [];
                    }
                }
                uploadLoading.value = false;
            } else {
                
                }
            }
        };
        return {
            handleChange
        };
    }

你可能感兴趣的:(前端,前端,前端框架,elementui,javascript)