vue之el-upload使用FormData多文件同时上传问题

 更新时间:2023年05月22日 15:00:30   作者:maidu_xbd  
这篇文章主要介绍了vue之el-upload使用FormData多文件同时上传问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

需求描述

使用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} 个文件`
      );
    },

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持程序员之家。

相关文章

  • VueX安装及使用基础教程

    VueX安装及使用基础教程

    这篇文章介绍了VueX安装及使用基础教程,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-01-01
  • Vue 基础语法之计算属性(computed)、侦听器(watch)、过滤器(filters)详解

    Vue 基础语法之计算属性(computed)、侦听器(watch)、过滤器(filters)详解

    计算属性就是 Vue 实例选项中的 computed,computed 的值是一个对象类型,对象中的属性值为函数,而且这个函数没办法接收参数,这篇文章主要介绍了Vue 基础语法之计算属性(computed)、侦听器(watch)、过滤器(filters)详解,需要的朋友可以参考下
    2022-11-11
  • vue+elementui实现动态控制表格列的显示和隐藏

    vue+elementui实现动态控制表格列的显示和隐藏

    这篇文章主要介绍了vue+elementui实现动态控制表格列的显示和隐藏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-04-04
  • vue路由的配置和页面切换详解

    vue路由的配置和页面切换详解

    这篇文章主要给大家介绍了关于vue路由的配置和页面切换的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-09-09
  • vue keep-alive多层级路由支持问题分析

    vue keep-alive多层级路由支持问题分析

    这篇文章主要介绍了vue keep-alive多层级路由支持,在文章开头给大家介绍了keep-alive使用问题,解决使用keep-alive include属性问题,本文给大家介绍的非常详细,需要的朋友可以参考下
    2023-03-03
  • 解决vue elementUI中table里数字、字母、中文混合排序问题

    解决vue elementUI中table里数字、字母、中文混合排序问题

    这篇文章主要介绍了vue elementUI中table里数字、字母、中文混合排序问题,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-01-01
  • ubuntu中利用nginx部署vue项目的完整步骤

    ubuntu中利用nginx部署vue项目的完整步骤

    Nginx是一款轻量级的Web服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,在BSD-like 协议下发行,下面这篇文章主要给大家介绍了关于ubuntu中利用nginx部署vue项目的相关资料,需要的朋友可以参考下
    2022-02-02
  • Vue中组件的数据共享分析讲解

    Vue中组件的数据共享分析讲解

    本文章向大家介绍vue组件中的数据共享,主要包括vue组件中的数据共享使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下
    2022-12-12
  • 详解关于Vue2.0路由开启keep-alive时需要注意的地方

    详解关于Vue2.0路由开启keep-alive时需要注意的地方

    这篇文章主要介绍了关于Vue2.0路由开启keep-alive时需要注意的地方,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-09-09
  • Vue-Router进阶之滚动行为详解

    Vue-Router进阶之滚动行为详解

    本篇文章主要介绍了Vue-Router进阶之滚动行为详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09

最新评论

?


http://www.vxiaotou.com