vue-element:文件上传七牛之key和异步的问题

本文介绍了一个使用Element UI的Excel文件上传组件实现,包括HTML代码和JS逻辑。组件限制上传文件类型为Excel,并检查文件大小不超过2MB。选择文件后,会请求上传token,然后上传文件至指定服务器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果图:

html 代码:

      <el-form-item label="Excel文件" :label-width="formLabelWidth" prop="excelurl">
              <el-upload class="avatar-uploader"
                ref="upload"
                action="//up.qbox.me/"
                :auto-upload="false"   
                :show-file-list="false"
                :on-success="handleFileSuccess"
                :on-error="handleFileError"
                :on-change="handleChange"
                :before-upload="beforeFileUpload"
                :data="uploadFile">
                <el-button slot="trigger" size="small" type="primary" class="file-select-btn">选择文件</el-button>
                <el-button class="upload-file-btn" size="small" type="primary" :disabled="isSuccessUpload" @click="uploadAction">上传</el-button>
              </el-upload>
              <el-input type="text" v-model="form.excelurl" class="upload-file-input" v-if="fileState" disabled></el-input>
              <el-button  size="small" type="primary" class="change-file-btn" v-if="btnState" @click="fileState=false;btnState=false">修改</el-button>
      </el-form-item>
其中: auto-upload="false"   为选择文件后不立即上传  on-change="handleChange"  为状态改变立即触发

Js代码:

     beforeFileUpload(file) {
        let filetype = file.name.slice(file.name.lastIndexOf('.'),file.name.length)
        if (filetype === '.xls' || filetype === '.xlsx') {
          // return true
        } else {
          this.$message.error('请上传EXCEL格式文件')
          return false
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('上传文件大小不能超过 2MB!')
          return  false;
        }        
      },
      handleChange(file){
        if(!this.fileState){
          this.$http.post(GET_UPLOAD_TOKEN, {}).then(res => {
            if (res.data.ret === 0) {
              this.uploadFile = {key:file.name,token : res.data.data.upToken}
              this.form.excelurl = file.name
              this.fileState = true
            }else{
              return false
            }
          })
        }
      },
      uploadAction(){
        this.$refs.upload.submit()
      },

上传成功:

注:
    在上传七牛时通过给key赋值,上传了原本的文件名,不通过七牛随机产生
     通过on-change函数在选择文件后,请求到token, 然后再上传文件 

更多专业前端知识,请上 【猿2048】www.mk2048.com
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值