废话不多说,先上代码
html 部分代码
<div class="upload-container sigleImageUpload">
<el-upload
class="avatar-uploader"
action="https://upload.qiniup.com"
:data="qiniuData"
accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
:show-file-list="false"
:on-success="handleSuccess"
:before-upload="beforeUpload"
>
<el-button v-else v-loading="loading" type="primary">点击上传</el-button>
</el-upload>
说明:actions是七牛云的地址,上传到图片到七牛云需要携带,token和key值,这个需要通过后端接口获取,:data="qiniuData
就是绑定这个数值,
主要思路: 在上传图片前beforeUpload
,获取到token和key值,赋值到qiniuData
上
data 数据
return {
loading: false,
qiniuData: {
token: '',
key: ''
}
}
},
js部分代码
// 上传图片之前获取token和key
beforeUpload(file) {
this.loading = true
const _self = this
// 由于获取数据是一个异步操作,所以此处用promise来处理
return new Promise((resolve, reject) => {
// getToken用来调用接口获取token 和key
getToken({
fileName: file.name // 我们后端要求传递个图片名称过去
}).then(res => {
const Data = res.data.data
if (res.data.code === 0) {
_self.qiniuData.key = Data.key
_self.qiniuData.token = Data.token
resolve(true)
} else {
reject(false)
this.loading = false
}
}).catch(err => {
console.log(err)
this.loading = false
reject(false)
})
})
},
// 上传成功时的回调
handleSuccess(data) {
// data.url就是上传成功后返回的图片在七牛云地址
console.log(data.url)
}
全部代码,我是封装成了一个组件,通过url与父组件双向数据绑定,当上传从后改变url父组件的url也改变了,就获取到了上传的图片地址
<template>
<div class="upload-container sigleImageUpload">
<el-upload
class="avatar-uploader"
action="https://upload.qiniup.com"
:data="qiniuData"
accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
:show-file-list="false"
:on-success="handleSuccess"
:before-upload="beforeUpload"
>
<!-- 展示上传成功后的图片-->
<img v-if="url" :src="url">
<el-button v-else v-loading="loading" type="primary">点击上传</el-button>
</el-upload>
</div>
</template>
<script>
// 获取token的api
import { getToken } from '@/api/common.js'
export default {
name: 'SingleImageUpload',
props: {
imgUrl: {
type: String,
default: ''
},
},
data() {
return {
loading: false,
qiniuData: {
token: '',
key: ''
}
}
},
computed: {
url: {
get() {
return this.imgUrl
},
set(val) {
this.$emit('update:imgUrl', val)
}
}
},
methods: {
handleSuccess(data) {
console.log(data)
if (data.url) {
this.url = data.url
}
this.loading = false
},
beforeUpload(file) {
this.loading = true
const _self = this
return new Promise((resolve, reject) => {
getToken({
fileName: file.name
}).then(res => {
const Data = res.data.data
if (res.data.code === 0) {
_self.qiniuData.key = Data.key
_self.qiniuData.token = Data.token
resolve(true)
} else {
reject(false)
this.loading = false
}
}).catch(err => {
console.log(err)
this.loading = false
reject(false)
})
})
}
}
}
</script>
网友评论