山东大学项目实训审计系统(五)上传文件

文章目录

一、上传文件功能讲解

1.选用工具

选用EementUI库中的upload组件,选择理由是其有优美的过度动画,不需要自己再去处理
山东大学项目实训审计系统(五)上传文件

2.具体代码

要将文件上传到我们的后端地址,故这里只用到组件中的FileList数组,设置upload组件不自动上传文件,在选中文件后将文件加入FileList数组,点击提交按钮后将数组作为参数发送后端请求,在选择删除文件时将文件从FileList数组中清除

组件代码

 <el-upload
        ref="upload"
        action="/"
        :file-list="fileList"
        :auto-upload="false"
        :on-change="handleChange"//绑定文件改变事件
        :on-remove="handleRemove"//绑定删除文件事件
        accept=".doc,.docx,.pdf"
        style="height: 320px;width: 100%;overflow-y:auto;margin-left: 10px"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div
          slot="tip"
          class="el-upload__tip"
          style="float: right;margin-right: 0px;font-size: 10px;font-weight: lighter;color: #a40002"
        >
        </div>
      </el-upload>
      <div style="text-align: center">
      <el-button
        type="primary"
        @click="TemplateUpload()"
        style="margin-top: 0px;"
        >上传模板</el-button
      >
    </div>

函数代码

//选中文件后判断文件类型,将正确文件加入fileList中等待上传
    handleChange(file) {
      // console.log(this.fileList);
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = testmsg === "docx";
      if (testmsg != "docx" && testmsg != "doc" && testmsg != "pdf") {
        this.$message({
          message: "上传文件只能是.doc/.docx/.pdf格式!",
          type: "warning"
        });
      } else {
        this.fileList.push(file);
      }
    },
    handleRemove(file) {
      this.fileList = this.fileList.filter(one => file.name !== one.name);
    },
    TemplateUpload() {
      if (this.fileList.length != 0) {
        this.$message.success("上传成功!");
        // alert("上传成功!");
        let formData = new FormData();
        this.fileList.forEach(file => {
          let newFile = file.raw;
          formData.append("files", newFile);
        });
        axios
          .post("https://baixx.site/api/template", formData, {
            headers: { token: sessionStorage.getItem("token") }
          })
          .then(res => {
            this.$emit("refresh_Template");
            this.close();
          });
      } else {
        this.$message.error("请选择上传的模板文件")
      }
    }

二、效果展示

山东大学项目实训审计系统(五)上传文件

上一篇:上传文件(二)


下一篇:上传照片组件