element-ui upload 组件 上传多个文件,只调用一次接口

element-ui upload 组件 要是一次上传多个文件,会自动请求多次,而现在想要上传多个文件放在一个请求里,可以把多个文件 fileList 合并在一个FormData里面,利用防抖策略使用debounce() 方法,上传多个文件后,只调用最后一次 submitUpload() 去调用上传接口 【如果想用这个文件,可以把api请求改下,就差不多可以使用了】

<template>
  <div>
    <div class="dragUpload">
      <el-upload
        :limit="7"
        ref="enclosureUpload"
        :file-list="fileList"
        accept=".xlsx, .xls, .pdf, .jpg, .jpeg, .gif, .png, .doc, .docx"
        :headers="tokens"
        :multiple="true"
        :show-file-list="false"
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-success="enclosureHandleSuccess"
        :on-exceed="handleExceed"
        :before-upload="handlebeforeUpload"
      >
        <el-button type="info" size="small" class="btn" @click="uploadmore">
          批量导入
        </el-button>
      </el-upload>

      <!-- 
       因为有了 debounce() 也可以不用 点击上传,debounce()自动 上传

        <el-button
        type="primary"
        :loading="uploadLoading"
        :disabled="uploadLoading"
        size="small"
        class="comfirm"
        @click="submitUpload"
        v-if="fileList.length"
      >
        确定上传
      </el-button>

      <div v-if="enclosureList.length" class="upload_idlist">
        <span>附件id列表:</span>
        <ul>
          <li v-for="item in enclosureList" :key="item">
            <i class="del_idlist" @click="delIdlist(item)">×</i>
            <span>{{ item }}</span>
          </li>
        </ul>

        <div class="aglingComfirm">
          <el-button type="primary" size="small" class="btn" @click="resetsubmitUpload">
            重新上传 ( 已有{{ enclosureList.length }}条数据 )
          </el-button>
          <el-button type="info" size="small" class="btn" @click="delUploadList">
            清除已上传数据
          </el-button>
        </div>
      </div> -->
    </div>
  </div>
</template>

<script>
import { uploadFile, uploadApi } from "@/api/xxxxxx"; //api 请求

export default {
  data() {
    return {
      tokens: {
        Authorization: localStorage.getItem("token"),
      },
      uploadLoading: false,
      fileList: [],
      enclosureList: [],
      exportLoading: false,
      timer: null,
    };
  },

  mounted() {},

  methods: {
    uploadmore(v) {
      console.log("批量导入", v);
    },

    // 过滤重复
    filterRepetition(arr) {
      let arr1 = []; //存id
      let newArr = []; //存新数组
      for (let i in arr) {
        if (arr1.indexOf(arr[i].name) == -1) {
          arr1.push(arr[i].name);
          newArr.push(arr[i]);
        }
      }
      return newArr;
    },

    handlebeforeUpload(file, fileList) {
      console.log("上传前", file, fileList);
    },

    // 修改 存放要上传的文件列表
    handleFileChange(file, fileList) {
      let arr = this.filterRepetition(fileList);
      if (arr.length !== fileList.length) {
        this.$message("上传重复文件,已过滤重复文件");
      }

      this.fileList = arr;

      // 上传文件后,自动把文件传给后台,这里做了一个防抖,等待500ms后在传给后台
      this.debounce(this.submitUpload, 500);
    },

    // element上传多个文件时,会把每个文件做个单独请求
    // 这里的方法是请求最后一次
    debounce(fn, waits) {
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }

      this.timer = setTimeout(() => {
        fn.apply(this, arguments); // 把参数传进去
      }, waits);
    },

    // 确定
    async submitUpload() {
      if (this.fileList.length === 0) {
        this.$message.success("请上传文件");
        return;
      }

      this.uploadLoading = true;
      let formData = new FormData(); //  用FormData存放上传文件
      this.fileList.forEach((file) => {
        formData.append("file", file.raw); // file.raw
      });

      // 确定上传 把在上传列表里的文件 合并到formData里面传给后台
      let res = await uploadApi(formData);
      console.log("结果;", res);

      if (res.isSuccess) {
        this.$message.success("上传成功");
        res.result = res.result || [];
        this.fileList = [];
        this.enclosureList = [];
        let arr = Object.prototype.toString.call(res.result);
        if (arr === "[object Array]") {
          this.enclosureList = res.result || [];
        }
        console.log("结果:", arr);
      }

      this.uploadLoading = false;
    },

    // 移除文件
    async delIdlist(val) {
      let flag = await this.$confirm(`确定移除吗?`);
      if (flag === "confirm") {
        this.enclosureList = this.enclosureList.filter((res) => res !== val);
      }
    },

    // 重新上传
    resetsubmitUpload() {
      this.enclosureList = [];
      this.fileList = [];
    },

    // 清除记录
    async delUploadList() {
      let flag = await this.$confirm(`确定清除所有附件ID吗?`);
      if (flag === "confirm") {
        this.enclosureList = [];
        this.fileList = [];
      }
    },

    // 取消
    approveCancel() {
      this.fileList = [];
      this.approve_dialog = false;
    },

    // 删除时的钩子
    onFileRemove(file, fileList) {
      console.log("删除时钩子-fileList", fileList);
      this.fileList = fileList;
    },
    // 删除之前钩子
    beforeFileRemove(file, fileList) {
      let flag = this.$confirm(`确定移除 ${file.name}`);
      return flag;
    },

    // 上传成功
    enclosureHandleSuccess(response, file, fileListile) {
      console.log("上传成功:", response, file, fileListile);
      this.uploadLoading = false;
    },

    // 上传失败
    enclosureHandleError(err, file, fileList) {
      this.$message({
        showClose: true,
        message: err,
        type: "error",
      });
      this.uploadLoading = false;
    },

    // 上传文件之前
    beforeUpload(file) {},

    // 导入
    handleExceed(files, fileList) {
      console.log("导入", files, fileList);
      this.$message.warning(`限制选择7个文件,本次选择了 ${files.length} 个文件`);
    },
  },
};
</script>

<style lang="scss" scoped></style>

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在使用 Element UI 的 el-upload 进行批量上传时,通过配置一些参数和编写一些代码可以实现只调用一次接口。 首先,需要设置 el-upload 组件的 action 属性为接口的地址,同时将属性 multiple 设置为 true,以支持多文件上传。 接下来,可以使用 el-upload 组件的 before-upload 属性,设置一个方法来处理上传前的逻辑。在这个方法中,可以获取到所有的文件文件列表,然后将它们合并成一个 FormData 对象,同时将这个对象作为参数传递给接口。这样,通过一次接口调用就可以实现批量上传。 具体操作如下所示: ```html <template> <el-upload action="your_api_url" :multiple="true" :before-upload="handleBeforeUpload" > <el-button type="primary">点击上传</el-button> </el-upload> </template> <script> export default { methods: { handleBeforeUpload(file) { // 获取所有的文件文件列表 const fileList = this.$refs.upload.uploadFiles; // 合并为 FormData 对象 const formData = new FormData(); fileList.forEach(file => { formData.append('files', file.raw); }); // 调用接口 this.$http.post('your_api_url', formData).then(response => { // 处理接口返回的数据 }); // 阻止 el-upload 组件默认的上传行为 return false; } } } </script> ``` 以上就是使用 Element UI 的 el-upload 组件实现批量上传调用一次接口的方法。通过设置适当的属性和编写相应的代码,可以在上传文件前合并所有文件为一个 FormData 对象,然后在接口调用一次性传递这个对象,从而实现批量上传

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端酱紫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值