1
<template>
<el-upload class="logo-uploader"
v-model="state.imageUrl"
action=""
:accept="`image/${accept}`"
:show-file-list="false"
:before-upload="beforeAvatarUpload"
>
<img :src="state.imageUrl" class='avatar-logo' v-if="state.imageUrl" />
<div class='icon-uploader' v-else>
<i class='el-icon-plus avatar-uploader-icon'/>
</div>
</el-upload>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator'
import { uploadToCDN } from '@/apis/coupon'
@Component
export default class Empty extends Vue {
@Prop({ default: 'png' })
accept!: string // 上传图片类型
@Prop({ default: 2 })
maxSize!: number // 上传图片限制大小
@Prop({ default: 500 })
imgWidthSize!: number // 上传图片宽度限制
@Prop({ default: 500 })
imgHeightSize!: number // 上传图片高度限制
state = {
imageUrl: ''
}
async beforeAvatarUpload(file: any) {
const type = file.type === `image/${this.accept}`
if (!type) {
this.$message.error(`图片格式错误!请上传${this.accept.toUpperCase()}格式的图片!`)
return false
}
const isLt2M = file.size / 1024 / 1024 < this.maxSize
if (!isLt2M) {
this.$message.error(`上传图片大小不能超过 ${this.maxSize}MB!`)
return false
}
const isSize = await new Promise((resolve, reject) => {
const _URL = window.URL || window.webkitURL
const img = new Image()
img.onload = () => {
if (img.width === this.imgWidthSize && img.height === this.imgHeightSize) {
resolve(true)
} else {
this.$message.error(`上传图片尺寸必须 ${this.imgWidthSize}px * ${this.imgHeightSize}px`)
reject()
}
}
img.src = _URL.createObjectURL(file)
})
if (type && isLt2M && isSize) {
const res = await uploadToCDN(file)
if (res.isValid()) {
this.state.imageUrl = (res.data as any).url
this.$emit('handleAvatarSuccess', this.state.imageUrl)
} else {
this.$message.error('图片上传失败')
}
}
return Promise.reject()
}
}
</script>
2