项目场景:
使用el-upload标签获取Java服务端签名直传
问题描述
第一次发送给oss的请求不会携带上数据而第二次就会携带上一次的数据
<el-upload class="avatar-uploader" action="# :data="policyObj" :show-file-list="false" :on-success="handleUploadSuccess" :before-upload="beforeUpload"> <img v-if="dataForm.coverUrl" :src="dataForm.coverUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload>
beforeUpload(file) { console.log("beforeUpload") this.$http({ url: this.$http.adornUrl(`/third/oss/policy`), method: 'post', params: this.$http.adornParams() }).then(({data}) => { console.log(data) if (data && data.code === 0) { this.policyObj.policy = data.data.policy this.policyObj.signature = data.data.signature this.policyObj.ossaccessKeyId = data.data.accessId this.policyObj.dir = data.data.dir this.policyObj.host = data.data.host this.policyObj.key = data.data.host+'/'+data.data.dir+this.getUUID()+file.name console.log(this.policyObj) } }) },
第二次请求
原因分析:
我也不清楚呜呜呜,我不是很懂前端来个前端大佬讲讲
解决方案:
使用Promise就可以成功实现
beforeUpload(file) { console.log("beforeUpload") return new Promise((resolve,reject)=>{ this.$http({ url: this.$http.adornUrl(`/third/oss/policy`), method: "get", params: this.$http.adornParams({}) }).then(({data})=>{ this.policyObj.policy = data.data.policy this.policyObj.signature = data.data.signature this.policyObj.ossaccessKeyId = data.data.accessId this.policyObj.dir = data.data.dir this.policyObj.host = data.data.host this.policyObj.key = data.data.host+'/'+data.data.dir+this.getUUID()+file.name resolve(true) }).catch(err=>{ reject(false) }) }) }