需求描述:

使用el-upload 手动上传方式进行文件上传【https://element.eleme.cn/#/zh-CN/component/upload】,当选择上传多个文件时,选择几个文件就会向后台发送几次请求。先后台要求同时一次请求发送多个文件,包括文件(如图中的file)和其他参数(如图中的graphName和userID)

解决方法:

通过FormData对象存放上传的文件和参数,将fileList中的文件存放在FormData中。具体见(3)多文件通过FormData存放上传

(1)补充知识点:FormData

FormData 数据形式为键值对,数据可通过XMLHttpRequest.send()方式发送出去

FormData.append(key,value):向FormData对象中添加一个键值对,如执行FormData.append(key1,value1)后FormData.append(key1,value2),key1对应值value1不会被覆盖,而是新增对应值value2

FormData.get(key):返回FormData对象中给定key对应的第一个值

FormData.getAll(key):返回FormData对象中给定key对应的所有值

FormData 具体使用见https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects

(2)单文件手动上传

:auto-upload="false"----关闭自动上传

:limit="1"----限制上传文件数量为1个

 :data="uploadData"----上传文件时的附带参数如userID

:action="batchImportUrl"----请求接口路径

具体见代码:

<el-dialog
      :visible.sync="batchImportDialogVisible"
      class="uploadFormDialog"
      width="40%"
      @close="closebatchImportForm"
    >
      <div slot="title">
        <span>{{ dialogTitle }}</span>
      </div>
      <el-upload
        class="upload-demo"
        ref="batchImport"
        :auto-upload="false"
        :on-error="batchImportError"
        :on-remove="batchRemoveFile"
        :before-upload="beforebatchImport"
        :on-progress="batchImportProgress"
        :on-success="batchImportSuccess"
        :on-change="batchImportChange"
        :file-list="fileList"
        :limit="1"
        :data="uploadData"
        :action="batchImportUrl"
      >
        <el-button
          slot="trigger"
          size="small"
          type="warning"
          @click="selectFile"
          >选取文件</el-button
        >
        <el-button size="small" type="success" @click="submitBatchImport">
          <span v-show="!isUploadFlag">上传到服务器</span>
          <span v-show="isUploadFlag">
            正在上传中
            <i class="el-icon-loading"></i>
          </span>
        </el-button>
        <div slot="tip" class="el-upload__tip">
          上传文件格式为json或rdf,点击
          <a class="download" @click="downloadTemplate">下载模板</a
          >&nbsp;&nbsp;可查看模板。
        </div>
      </el-upload>
    </el-dialog>
  // 批量导入新的图谱信息
    batchAddGraph() {
      this.dialogTitle = "批量创建新图谱";
      this.batchImportDialogVisible = true;
      this.batchImportUrl = " /api/manage/common/graph/add/batch";
    },
    // 批量导入已存在的图谱信息
    batchUpdateGraph(name) {
      this.dialogTitle = `批量导入${name}图谱`;
      this.uploadData = {
        userID: "",
        graphName: this.graphName
      };
      this.batchImportDialogVisible = true;
      this.batchImportUrl = " /api/manage/common/graph/update/increment";
    },
    // 提交批量导入
    submitBatchImport() {
      if (this.$refs.batchImport.uploadFiles.length == 0) {
        this.$message.warning("请选择要上传的文件");
        return;
      }
      this.loading = this.$loading({
        lock: true,
        text: "正在导入图谱,请稍等",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.6)"
      });
      this.isUploadFlag = true;
      this.$refs.batchImport.submit();
    },
    // 选择文件
    selectFile() {
      this.$refs.batchImport.clearFiles();
    },
    // 关闭对话框-清除照片
    closebatchImportForm() {
      this.isUploadFlag = false;
      this.$refs.batchImport.clearFiles();
    },
    // 批量上传成功的钩子
    batchImportSuccess(res, file, fileList) {
      if (res.respCode === "200") {
        this.$message.success("批量导入成功");
        this.graphDialogVisible = false;
        this.isUploadFlag = false;
        this.getGraphInfo();
      } else {
        this.$message.error(res.respDesc);
      }
      this.batchImportDialogVisible = false;
      this.loading.close();
    },
    // 批量导入失败时的钩子
    batchImportError() {
      this.$message.error(" 批量导入失败");
      this.isUploadFlag = false;
      this.loading.close();
    },
    // 批量导入-文件状态改变时的钩子
    batchImportChange(file, fileList) {
      // console.log("文件状态改变时的钩子");
      if (!/.(json|rdf)$/.test(file.name)) {
        this.$refs.batchImport.uploadFiles = [];
        this.$message.warning("请选择json或rdf格式的文件");
      }
    },
    // 上传文件前的钩子
    beforebatchImport(file) {
      // console.log("上传文件前的钩子");
    },
    // 文件上传时的钩子
    batchImportProgress(event, file, fileList) {
      // console.log("==文件上传时progress==", file);
    },
    //文件列表移除文件时的钩子
    batchRemoveFile() {
      // console.log("移除");
    }

(3)多文件通过FormData存放上传

:file-list="fileList" 配置一个数组用于接收上传的文件列表

multiple 选择文件时允许多选

具体代码:

<el-dialog
      :visible.sync="batchImportDialogVisible"
      class="uploadFormDialog"
      width="40%"
      @close="closebatchImportForm"
      :close-on-click-modal="false"
    >
      <div slot="title">
        <span>{{ dialogTitle }}</span>
      </div>
      <div v-if="dialogTitle == '批量创建新图谱'" class="input-wrapper">
        <div class="name">图谱名称</div>
        <el-input v-model="bacthImportGraphName" clearable></el-input>
      </div>
      <el-upload
        class="upload-demo"
        ref="batchImport"
        :auto-upload="false"
        accept=".json,.csv,.rdf"
        :on-remove="batchRemoveFile"
        :on-change="batchImportChange"
        :on-exceed="batchImportExceed"
        :file-list="fileList"
        :limit="2"
        :action="batchImportUrl"
        multiple
      >
        <el-button
          slot="trigger"
          size="small"
          type="warning"
          @click="selectFile"
          >选取文件</el-button
        >
        <el-button size="small" type="success" @click="submitBatchImport">
          <span v-show="!isUploadFlag">上传到服务器</span>
          <span v-show="isUploadFlag">
            正在上传中
            <i class="el-icon-loading"></i>
          </span>
        </el-button>
        <div slot="tip" class="el-upload__tip">
          上传文件格式为json、rdf或csv,点击
          <a class="download" @click="downloadTemplate">下载模板</a
          >&nbsp;&nbsp;可查看模板。
        </div>
      </el-upload>
    </el-dialog>
// 选择文件
    selectFile() {
      // this.$refs.batchImport.clearFiles();
    },
    // 批量导入新的图谱信息
    batchAddGraph() {
      this.dialogTitle = "批量创建新图谱";
      this.batchImportDialogVisible = true;
      this.uploadData.graphName = this.bacthImportGraphName; //绑定数据
      this.batchImportUrl = " /api/manage/common/graph/add/batch";
    },
    // 批量导入已存在的图谱信息
    batchUpdateGraph(name) {
      this.dialogTitle = `批量导入${name}图谱`;
      this.uploadData = {
        userID: "",
        graphName: this.graphName
      };
      this.batchImportDialogVisible = true;
      this.batchImportUrl = " /api/manage/common/graph/update/increment";
    },
    // 批量导入-文件状态改变时的钩子
    batchImportChange(file, fileList) {
      // console.log("文件状态改变时的钩子");
      this.fileList = fileList;
    },
    //文件列表移除文件时的钩子
    batchRemoveFile(file, fileList) {
      // console.log("文件列表移除文件时的钩子");
      this.fileList = fileList;
    },
    // 提交批量导入
    submitBatchImport() {
      if (this.dialogTitle == "批量创建新图谱") {
        this.uploadData.graphName = this.bacthImportGraphName;
        // 1.提交批量创建新图谱
        if (!this.bacthImportGraphName) {
          this.$message.warning("请填写图谱名称");
          return;
        }
      }
      if (this.$refs.batchImport.uploadFiles.length == 0) {
        this.$message.warning("请选择要上传的文件");
        return;
      }
      this.loading = this.$loading({
        lock: true,
        text: "正在导入图谱,请稍等",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.6)"
      });
      this.isUploadFlag = true;
      // this.$refs.batchImport.submit();
      let formData = new FormData(); //  用FormData存放上传文件
      this.fileList.forEach(file => {
        formData.append("file", file.raw); //文件
      });
      formData.append("graphName", this.uploadData.graphName);
      formData.append("userID", "13013");

      axios
        .post(this.batchImportUrl, formData, {
          headers: { "Content-Type": "multipart/form-data" } //设置请求头请求格式为JSON
        })
        .then(res => {
          this.$message.success(res.data.respDesc);
          this.graphDialogVisible = false;
          this.isUploadFlag = false;
          this.bacthImportGraphName = "";
          this.getGraphInfo();
          this.loading.close();
          this.batchImportDialogVisible = false;
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 关闭对话框-清除照片
    closebatchImportForm() {
      this.isUploadFlag = false;
      this.$refs.batchImport.clearFiles();
    },
    // 批量导入-定义超出限制时的行为
    batchImportExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 2 个文件,本次选择了 ${
          files.length
        } 个文件,共选择了 ${files.length + fileList.length} 个文件`
      );
    },

 

Logo

前往低代码交流专区

更多推荐