匆忙分享,都在代码里了😬
<template>
<!-- uploadConfig参数可以按需传参,不必全部传过去 -->
<el-upload class="uploader-wrapper"
:action="uploadConfig.uploadUrl"
:show-file-list="false"
:data="uploadConfig"
:on-success="handleAvatarSuccess"
:on-error="handleAvatarError"
:before-upload="beforeAvatarUpload">
<img v-if="pictureUrl"
:src="pictureUrl"
class="uploader">
<i v-else
class="el-icon-plus uploader-wrapper-icon"></i>
</el-upload>
</template>
<script>
/**
* 用于将图片或文件上传到阿里云,分两步,第一步拿到上传接口的配置信息,第二步上传操作,成功后第一步中返回的文件链接才会生效
* 接收一个pictureUrl用于回显图片
* 暴露一个uploadSuccess上传成功钩子,目前只返回了文件/图片的阿里云地址
*/
export default {
name: 'imgUpload',
props: ['pictureUrl'],
data () {
return {
uploadConfig: {
uploadUrl: '',
fileUrl: ''
}
}
},
methods: {
// 图片上传
handleAvatarSuccess (response, file, fileList) {
this.$emit('uploadSuccess', this.uploadConfig.fileUrl)
},
handleAvatarError () {
this.$message.error('图片上传失败请重试')
},
async beforeAvatarUpload (file) {
this.uploadConfig = await this.getALiYunConfig(file) // 阻塞一下,获取到uploadConfig后,再判定beforeUpload钩子执行完,不然action报错(没有值就开始执行上传请求导致)
},
// 获取阿里云配置信息,包含签名和上传地址等
getALiYunConfig (file) {
return new Promise((resolve, reject) => {
this.$post('xxx', { "contentType": file.type })
.then(res => {
if (res.code === 200) {
// 已经携带了上传成功后的文件地址
resolve(res.data)
} else {
this.$message.warning('获取上传信息失败请重试')
}
})
})
}
},
}
</script>
<style lang="less" scoped>
.uploader-wrapper {
& /deep/ .el-upload {
border: 1px solid #999;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
}
.uploader-wrapper-icon {
font-size: 16px;
color: #999;
width: 60px;
height: 60px;
line-height: 60px;
text-align: center;
}
.uploader {
width: 60px;
height: 60px;
display: block;
}
</style>