vue2+element-ui批量导入方法并判断上传的文件是否为xls或xlsx

业务需求:

代码结构:

<el-dialog
    title="批量导入"
    :close-on-click-modal="true"
    @close="close()"
    :visible="true"
    width="35%"
    :center="true"
  >
    <div class="el-dialog-div">
      <!-- 头部区域布局 -->
      <div class="header_area">
        <div class="header_word">
          <p>专家导入</p>
        </div>
        <div class="header_list">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-download"
            plain
            @click="downloadTemplate"
            >下载模板</el-button
          >
        </div>
      </div>
      <el-upload
        class="upload-demo"
        ref="upload"
        :action="uploadUrl"
        :file-list="fileList"
        :auto-upload="false"
        :headers="{ token: $cookie.get('token') }"
        :multiple="false"
        :show-file-list="true"
        :on-change="handleChange"
        :on-remove="handleRemove"
        :limit="1"
      >
        <el-button
          slot="trigger"
          size="small"
          type="primary"
          icon="el-icon-plus"
          plain
          :disabled="fileList.length>0"
          >专家文件选择
        </el-button>
      </el-upload>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="close()">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :uploading="uploading"
        >确定</el-button
      >
    </span>
  </el-dialog>

下载模板方法:

// 下载模板
    downloadTemplate() {
      // 模板文件的下载链接
      const templateFileUrl = "/uploads/template.xlsx"; //后端给一个服务器模板链接
      // 创建一个链接元素
      const link = document.createElement("a");
      link.href = templateFileUrl;
      link.target = "_blank";
      link.download = "模板.xlsx"; // 下载的文件名
      link.style.display = "none";
      // 将链接元素添加到 DOM 中
      document.body.appendChild(link);
      // 模拟点击下载链接
      link.click();
      // 移除链接元素
      document.body.removeChild(link);
    },

提交上传方法:

1.先做类型判断 大小判断 是否上传

// 检查是否选择了文件
      if (this.fileList.length <= 0) {
        this.$message.error("请先选择要导入的文件");
        return;
      }
      // 检查文件类型是否是 Excel
      const isExcel =
        this.fileList[0].type === "application/vnd.ms-excel" ||
        this.fileList[0].type ===
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      if (!isExcel) {
        this.$message.error("仅支持xls、xlsx格式的文件!");
        return;
      }
      // 检查文件大小是否符合限制
      const isSizeValid = this.fileList[0].size / 1024 / 1024 < 10;
      if (!isSizeValid) {
        this.$message.error("文件大小不能超过10MB");
        return;
      }

2.提交后端方法

this.uploading = true;
      // 创建 FormData 对象,用于将文件作为表单字段上传
      const formData = new FormData();
      formData.append("file", this.fileList[0].raw);
      // 发送文件上传请求
      this.$http({
        url: this.$http.adornUrl(
          "/professorInfo/importProfessorInfo",
          "member"
        ),
        method: "post",
        headers: { "Content-Type": "multipart/form-data" },
        data: formData,
      })
        .then(({ data }) => {
          console.log(data, "000000000");
          // 处理上传成功的逻辑
          if (data && data.code === "0") {
            // 上传成功的处理逻辑
            this.$message({
              message: `成功导入${data.data.successNum}条数据`,
              type: "success",
              duration: 2000,
              onClose: () => {
                this.$emit("refresh-data-list");
                this.close();
              },
            });
          } else {
            // 上传失败的处理逻辑
            this.$message.error(data.msg);
            // 其他逻辑处理...
          }
          this.uploading = false;
          this.$emit("refresh-data-list");
          this.close();
        })
        .catch((error) => {
          // 处理请求异常的逻辑
          this.$message.error(data.msg);
          console.error(error);
          // 其他逻辑处理...
          this.uploading = false;
        });

3.完整代码

dataFormSubmit() {
      // 检查是否选择了文件
      if (this.fileList.length <= 0) {
        this.$message.error("请先选择要导入的文件");
        return;
      }
      // 检查文件类型是否是 Excel
      const isExcel =
        this.fileList[0].type === "application/vnd.ms-excel" ||
        this.fileList[0].type ===
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      if (!isExcel) {
        this.$message.error("仅支持xls、xlsx格式的文件!");
        return;
      }
      // 检查文件大小是否符合限制
      const isSizeValid = this.fileList[0].size / 1024 / 1024 < 10;
      if (!isSizeValid) {
        this.$message.error("文件大小不能超过10MB");
        return;
      }
      this.uploading = true;
      // 创建 FormData 对象,用于将文件作为表单字段上传
      const formData = new FormData();
      formData.append("file", this.fileList[0].raw);
      // 发送文件上传请求
      this.$http({
        url: this.$http.adornUrl(
          "/professorInfo/importProfessorInfo",
          "member"
        ),
        method: "post",
        headers: { "Content-Type": "multipart/form-data" },
        data: formData,
      })
        .then(({ data }) => {
          console.log(data, "000000000");
          // 处理上传成功的逻辑
          if (data && data.code === "0") {
            // 上传成功的处理逻辑
            this.$message({
              message: `成功导入${data.data.successNum}条数据`,
              type: "success",
              duration: 2000,
              onClose: () => {
                this.$emit("refresh-data-list");
                this.close();
              },
            });
          } else {
            // 上传失败的处理逻辑
            this.$message.error(data.msg);
            // 其他逻辑处理...
          }
          this.uploading = false;
          this.$emit("refresh-data-list");
          this.close();
        })
        .catch((error) => {
          // 处理请求异常的逻辑
          this.$message.error(data.msg);
          console.error(error);
          // 其他逻辑处理...
          this.uploading = false;
        });
    },

猜你喜欢

转载自blog.csdn.net/shi15926lei/article/details/132718369