vue+elementUI上传图片单张/多张至七牛云,组件代码
<template>
<div>
<el-upload
:action="actionUrl"
list-type="picture-card"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:on-success="handleSuccess"
:before-upload="beforeUpload"
:file-list="fileList"
:limit="limit"
:multiple="multiple"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
</div>
</template>
<script>
import { uploadToken } from '@/api/qiniu'
export default {
props: {
limit: {
type: Number,
default: 1
},
multiple: {
type: Boolean,
default: false
}
},
data() {
return {
actionUrl: 'http://upload.qiniu.com/',
dialogImageUrl: '',
dialogVisible: false,
fileList: [],
token: ''
}
},
methods: {
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
async beforeUpload(file) {
if (!this.token) {
const tokenData = await uploadToken()
this.token = tokenData.token
}
const timestamp = (new Date()).getTime()
const key = `image/${timestamp}`
const policy = {
scope: key
}
const encodedPolicy = window.btoa(JSON.stringify(policy))
const signature = hex_md5(encodedPolicy)
const uploadToken = `token=${this.token}&key=${key}&policy=${encodedPolicy}&signature=${signature}`
file.uploadToken = uploadToken
},
handleSuccess(response, file, fileList) {
const imageUrl = `http://your-qiniu-domain/${response.key}`
this.$emit('success', imageUrl)
}
}
}
</script>
在这个代码实例中,我们使用了Element UI的<el-upload>
组件来处理图片的上传。我们设置了七牛云上传所需的actionUrl
和上传前的beforeUpload
处理函数,在这个处理函数中我们获取上传凭证(token),并且将它添加到上传的请求中。handleSuccess
方法用于处理图片上传成功后的响应,并且发出一个自定义的\`s
评论已关闭