上传txt文件

2022-03-28  本文已影响0人  一只鱼_d589

模版

<el-upload
                class="upload-demo"
                ref="upload"
                accept=".txt"
                action=""
                :limit="1"
                :http-request="httpRequest"
                :auto-upload="false"
                :file-list="fileList"
                :on-change="handleFileChange"
              >
              <el-button slot="trigger" size="small" type="warning" style="margin-top: 6px;">选取文件</el-button>
              <div slot="tip" class="el-upload__tip" style="color: #ee4234">
                {{ tips }}
              </div>
 </el-upload>

data

fileList: [],
tips: "只能上传txt格式的文件",

methods

handleFileChange(file, fileList) {
        let that = this;
        that.beforeUpload(file);
        that.file= file;
        that.fileList = [fileList[fileList.length - 1]]; // 这一步,是 展示最后一次选择的dat文件
        if (that.fileList.length) {
        let params = new FormData();
        that.fileList.forEach(item => {
          params.append("MultipartFile", item.raw)
        })
        var config = {
          // 添加请求头
            headers: { 
              "Content-Type": "multipart/form-data;" 
            },
        };
        API.addDamageDegree(params, config).then(function (res) {
          if (res.code == "200") {
              that.isVisible = false
                that.$emit('success')
          } else {
            that.$message.error({
              showClose: true,
              message: res.data.message,
              duration: 5000,
            });
          }
        })
        .catch(function (error) {
          that.buttonLoading = false;
          that.$message.error({
            showClose: true,
            message: "请求出现异常",
            duration: 2000,
          });
        });
      }
      
    },
httpRequest(param) {
      let fileObj = param.file; // 相当于input里取得的files
      let fileName = fileObj.name;
      let formData = new FormData(); // FormData 对象
      formData.append("MultipartFile", fileObj); // 文件对象
      formData.append("fileCreateName", fileName);
      this.$emit("upload", formData);
    },

    isFormatValid(type) {
      let pStrDAt = /\.txt?$/i;
      return pStrDAt.test(type);
    },
    beforeUpload(file) {
      let fileName = file.name;
    //   this.$emit("update:fileName", fileName);
      let isDat = this.isFormatValid(fileName);
      if (!isDat) {
        this.tips = "当前选择的文件格式不正确,请重新选择!";
      } else {
        this.tips = "";
      }
      return isDat;
    },
上一篇下一篇

猜你喜欢

热点阅读