需求:1.表单输入信息

2.上传Excel附件

3.下载附件模板

4.限制上传文件的格式、文件的大小、文件的数量

5.将表单和Excel文件一起提交给后端

  • 效果图:

  1. 样式部分

 <el-form ref="form" :model="peopleform" label-width="150px">
      <el-form-item>
        <el-button
          type="primary"
          plain
          size="medium"
          icon="el-icon-download"
          style="float:right;"
          @click="downloads"
        >下载模板</el-button>
      </el-form-item>

      <el-form-item label="姓名">
        <el-input v-model="peopleform.name"></el-input>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="peopleform.phone"></el-input>
      </el-form-item>
      <el-form-item label="地址">
        <el-input v-model="peopleform.address"></el-input>
      </el-form-item>
      <el-form-item label="上传附件">
        <el-upload
          drag
          action="#"
          :http-request="httpRequest"
          :before-upload="beforeUpload"
          :on-exceed="handleExceed"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处,或
            <em>点击上传</em>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="success" size="medium" @click="submit" style="margin:0 !important">提交</el-button>
      </el-form-item>
    </el-form>
  1. data部分代码

 data () {
    return {
      peopleform: {
        name: '',
        phone: '',
        address: '',
      },
      fileList: []
    }
  },
  1. method中的代码

 methods: {
    // 覆盖默认的上传行为
    httpRequest (raw) {
      this.fileList.push(raw)
    },
    // 上传前
    beforeUpload (file) {
      let fileSize = file.size
      const FIVE_M = 2 * 1024 * 1024
      //不允许上传大于2M
      if (fileSize > FIVE_M) {
        this.$message.error("最大上传2M")
        return false
      }
      //判断文件类型,必须是xlsx格式
      let fileName = file.name
      let reg = /^.+(\.xlsx)$/
      if (!reg.test(fileName)) {
        this.$message.error("只能上传xlsx!")
        return false
      }
      return true
    },
    // 文件数量提醒
    handleExceed () {
      this.$message({ type: 'error', message: '最多支持1个附件上传' })
    },
    //提交
    async submit () {
      const params = new FormData()
      this.fileList.forEach((x) => {
        params.append('file', x.file)
      })
      params.append('name', this.peopleform.name)
      params.append('phone', this.peopleform.phone)
      params.append('address', this.peopleform.address)
      const res = await this.axios.post("这里填路径", params)
      if (res) {
        this.$message.success("上传成功!")
      }

    },
    //设置下载文件
    downloads () {
      let a = document.createElement("a")
      a.href = "/data/datas/main_ventilator_excel.xlsx"
      a.download = "main_ventilator_excel.xlsx" //设置下载文件文件名,这里加上.xlsx指定文件类型
      a.style.display = "none"
      document.body.appendChild(a)
      a.click()
      a.remove()
    }

  }

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐