借助el-upload实现文件上传

需求效果:

<el-dialog title="上传割接记录" :visible.sync="dialogVisible" width="50%">
      <el-form inline class="app-form">
        <el-row class="row-2" style="text-align:center;">
          <el-form-item label="割接操作记录">
            <el-input v-model="fileForm.operfile" readonly></el-input>
          </el-form-item>
          <el-form-item prop="operfile">
            <el-upload
              class="upload-demo"
              ref="uploadBox"
              action="#"
              name="operfile"
              :on-change="operFile"
              :auto-upload="false"
              :limit="1"
              :on-exceed="() => $message.warning('一次只能上传1个文件!')"
            >
              <el-button
                slot="trigger"
                icon="el-icon-document-add"
                type="primary"
                >浏览</el-button
              >
            </el-upload>
          </el-form-item>
        </el-row>
        <el-row class="row-2" style="text-align:center;">
          <el-form-item label="业务验证">
            <el-input v-model="fileForm.checkfile" readonly></el-input>
          </el-form-item>
          <el-form-item prop="checkfile">
            <el-upload
              class="upload-demo"
              ref="uploadBox2"
              action="#"
              name="checkfile"
              :on-change="checkFile"
              :auto-upload="false"
              :limit="1"
              :on-exceed="() => $message.warning('一次只能上传1个文件!')"
            >
              <el-button
                slot="trigger"
                icon="el-icon-document-add"
                type="primary"
                >浏览</el-button
              >
            </el-upload>
          </el-form-item>
        </el-row>
        <el-row class="row-2" style="text-align:center;">
          <el-form-item>
            <el-button type="primary" @click="submitHandle">确认</el-button>
            <el-button @click="closeDialog">取消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>
  data() {
    return {
      dialogVisible: false,
      fileForm: {
        taskid: '', // 任务ID	taskid
        opertype: '', // 操作类型	opertype
        operfile: '', // 操作记录路径
        checkfile: '', // 校验记录路径
      },
      fileList: [],
    }
  },

 


  methods: {

    // 取消&&完成&&上传操作文件页面的确认
    getoperroottask(form) {
      this.$utils
        .doRequest('cno/res/tacacsroot/operroottask', form, 'post')
        .then(res => {
          if (res.code == '0000') {
            this.$message.success(res.msg)
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          this.$message.error(err.msg)
        })
    },

    operFile(file) {
        console.log(file);
      /**
       * 可以在选取文件后直接拿到 file对象进行存储
       * 不能直接push 要始终保证 fileList 是两个对象,因此,需要进行判断
       */

      let checkFileExte = ['xls', 'xlsx'].includes(file.name.split('.')[1])
      // 直接返回,但是 upload 组件下的list 会有提示,需要做处理
      if (!checkFileExte)
        return (
          this.$message.warning('上传文件只能是xls、xlsx格式!'),
          this.$refs.uploadBox.clearFiles()
        )

      if (this.fileList.find(file => file.type === 'operFile'))
        // 替换
        this.fileList[
          this.fileList.findIndex(file => file.type === 'operFile')
        ] = { file: file.raw, type: 'operFile' }
      else this.fileList.push({ file: file.raw, type: 'operFile' })
      this.fileForm.operfile = file.name
    },

    checkFile(file) {
      /**
       * 可以在选取文件后直接拿到 file对象进行存储
       * 不能直接push 要始终保证 fileList 是两个对象,因此,需要进行判断
       */

      let checkFileExte = ['xls', 'xlsx'].includes(file.name.split('.')[1])
      // 直接返回,但是 upload 组件下的list 会有提示,需要做处理
      if (!checkFileExte)
        return (
          this.$message.warning('上传文件只能是xls、xlsx格式!'),
          this.$refs.uploadBox2.clearFiles()
        )

      if (this.fileList.find(file => file.type === 'checkFile'))
        //    替换
        this.fileList[
          this.fileList.findIndex(file => file.type === 'checkFile')
        ] = { file: file.raw, type: 'checkFile' }
      else this.fileList.push({ file: file.raw, type: 'checkFile' })
      this.fileForm.checkfile = file.name
    },

    // 确认按钮点击事件
    submitHandle() {
      if (this.fileForm.checkfile === '' || this.fileForm.operfile === '') {
        this.$message({
          message: '请选择要上传的文件',
          duration: 3000,
          type: 'warning',
        })
      } else {
        /**
         * fielList 就是也要上传的文件列表,直接调用接口即可,不需要使用upload submit 方法
         * formData 尽量不要存储
         * 接下来就是创建formData 进行文件传输
         */

        let formData = new FormData()
        // 添加到 formData type 是选取文件时给的文件标记,也是上传的文件标记
        this.fileList.forEach(file => formData.append(file.type, file.file))
        // 调用接口欧
        this.getoperroottask(formData)
        this.closeDialog()
      }
    },

    closeDialog() {
      this.dialogVisible = false
      this.fileForm.checkfile = ''
      this.fileForm.operfile = ''
      this.$refs.uploadBox.clearFiles()
      this.$refs.uploadBox2.clearFiles()
    },
  },

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
el-uploadElement UI中的一个文件上传组件,它可以帮助我们轻松地实现文件上传功能。下面是一个简单的示例,演示如何使用el-upload实现文件上传: 1. 首先需要安装Element UI库并引入相关文件,可以在Vue的入口文件中添加以下代码: ``` import Vue from 'vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI) ``` 2. 接着在Vue组件中添加el-upload组件,例如: ``` <template> <el-upload class="upload-demo" action="/api/upload" :on-success="handleSuccess" :before-upload="beforeUpload" :on-error="handleError" :limit="1" :auto-upload="false" :file-list="fileList"> <el-button size="small" type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload> </template> <script> export default { data() { return { fileList: [] } }, methods: { beforeUpload(file) { const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' const isLt2M = file.size / 1024 / 1024 < 2 if (!isJPG) { this.$message.error('上传头像图片只能是 JPG/PNG 格式!') } if (!isLt2M) { this.$message.error('上传头像图片大小不能超过 2MB!') } return isJPG && isLt2M }, handleSuccess(response, file, fileList) { this.fileList = fileList this.$message.success('上传成功') }, handleError(error, file, fileList) { this.fileList = fileList this.$message.error('上传失败') } } } </script> ``` 在上面的示例中,el-upload组件有多个属性和事件,其中比较重要的包括: - action: 上传文件的URL地址。 - on-success: 文件上传成功后的回调函数。 - before-upload: 文件上传前的钩子函数,用于校验文件类型和大小等。 - on-error: 文件上传失败后的回调函数。 - limit: 限制上传文件的数量。 - auto-upload: 是否在选取文件后立即上传。 - file-list: 已上传的文件列表。 通过以上步骤,就可以使用el-upload实现文件上传功能了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值