vue-element:文件上傳七牛之key和異步的問題


效果圖:

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, 然后再上傳文件 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM