七牛、阿里雲oss文件上傳前需要先獲取key時利用element ui的上傳插件操作方法


<el-form-item label="Excel文件" :label-width="formLabelWidth" prop="excelurl">
              <el-upload class="avatar-uploader"
                ref="upload"
                action="//uploadrul/"
                :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關鍵是利用this.$refs.upload.submit()手動觸發上傳
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()
      },
            ```


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章