vue文件导入判断文件类型及文件名,formData格式处理

判断文件类型(是否为指定类型)

  • nameArr: [], //已导入的文件名
 // 截取文件名后缀
      let fileName = file.name;
      let pos = fileName.lastIndexOf(".");
      let lastName = fileName.substring(pos, fileName.length);
      if (lastName.toLowerCase() !== ".csv" && lastName.toLowerCase() !== ".xlxs" && lastName.toLowerCase() !== ".xml") {
        this.$message.error("文件必须为.csv,.xlxs,.xml类型");
        // 清空文件列表
        const newFileList = this.fileList.slice();
        newFileList.splice(0, 1);
        this.fileList = newFileList;
      }
      else if (this.nameArr.includes(this.folder.name)) {
        this.$message.error("表名命名重复");
      }
  • 完整代码
  <el-dialog title="表名" :visible.sync="dialogVisible1" width="30%">
      <el-form ref="folder" :model="folder" label-width="80px">
        <el-form-item label="表名:">
          <el-input maxlength="10" v-model="folder.name"></el-input>
        </el-form-item>
        <el-form-item style="display: flex; flex-direction: row-reverse">
          <el-button>
            <el-upload :show-file-list="false" action="" class="upload-demo" ref="upload" :on-change="importData"
              accept=".csv" :auto-upload="false">
              确定
            </el-upload>
          </el-button>
          <el-button @click="dialogVisible1 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
 //导入数据
    async importData(file) {
      // 截取文件名后缀
      let fileName = file.name;
      let pos = fileName.lastIndexOf(".");
      let lastName = fileName.substring(pos, fileName.length);
      if (lastName.toLowerCase() !== ".csv" && lastName.toLowerCase() !== ".xlxs" && lastName.toLowerCase() !== ".xml") {
        this.$message.error("文件必须为.csv,.xlxs,.xml类型");
        // 清空文件列表
        const newFileList = this.fileList.slice();
        newFileList.splice(0, 1);
        this.fileList = newFileList;
      }
      else if (this.nameArr.includes(this.folder.name)) {
        this.$message.error("表名命名重复");
      }
      else {
        let files = {};
        files = file.raw;
        let formData = new FormData();
        formData.append("file", files);
        console.log(this.$route.query.id);
        console.log("000------", this.folder.name);
        const { data } = await ImportDataToDB(
          this.folder.name,
          this.$route.query.id,
          formData
        );
        console.log(this.data[0].type, "3==");
        const form = {
          type: this.data[0].type,
          parentid: this.$route.query.id,
          name: this.folder.name,
        };
        //创建数据集
        await insert(form);
        this.getList();
        this.dialogVisible1 = false;
      }
    },

你可能感兴趣的:(导入文件,vue.js,javascript,前端)