效果图:
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, 然后再上传文件