【elementui upload组件上传多个文件只调用一次接口】

ElementUI上传组件:批量文件一次调用接口
本文介绍了如何在ElementUI的Upload组件中设置auto-upload为false,然后覆盖默认上传行为,通过http-request自定义上传实现,并利用FormData添加多个文件,以确保在上传多个文件时仅调用一次接口。

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

要求:上传多个文件,但只调用一次接口

要求
上传多个文件,但只调用一次接口

思路

  1. auto-upload 设为false,取消自动上传
  2. http-reques 覆盖默认的上传行为,可以自定义上传的实现
  3. 使用 new FormData(),用append往传参里push多个文件或参数
  4. 触发upload组件的上传按钮

代码案例

<template>
  <div class="wrapBox">
    <el-upload ref="upload" :action="action" :file-list="fileList" :on-success="uploadSuccess" :http-request="httpRequest" :auto-upload="false">
      <el-button slot="trigger" type="primary">选取文件</el-button>
    </el-upload>
      <el-button type="success" @click="submit">上传</el-button>
  </div>
</template>
<script>
import axios from "axios";
export default {
  data() {
    return {
      formData: new FormData(),
      fileList: [],
      action: '', // 上传地址
    };
  },
  methods: {
    
    // 覆盖默认的上传行为,可以自定义上传的实现
    httpRequest(param) {
      // this.formData.append(自定义文件名, 文件);
      this.formData.append("file", param.file);
      // this.formData.append("filename1", param.file);
 
    },

    //提交上传
    submit() {
      //触发upload组件的上传,会自动调用 httpRequest 方法,有几个文件就会执行几次
      this.$refs.upload.submit(); 
      // 可以用append方法,添加自定义的参数
      this.formData.append("spatialReferenceZone", 36); 
      let headers = {
        headers: { "Content-Type": "multipart/form-data" },
      };
      // axios.post( 接口,  参数 , 请求头);
      axios.post(this.action, this.formData, headers);
    },


    //文件上传成功
    uploadSuccess(response, file, fileList) {
      if (response.success) {
        //这个就是返回文件地址
        console.log(response.msg);
        this.$message({
          message: `${file.name}成功上传`,
          type: "success",
        });
      }
    },
  },
};
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值