七牛、阿里云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()
      },
            ```


你可能感兴趣的:(js)