结构:
<template><div><el-upload class="avatar-uploader" action="#" :show-file-list="false" // :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :http-request="upload"> // 自定义上传配置,on-success钩子函数也不会继续触发<img v-if="staffPhoto" // 判断图片地址的有无 有的话显示这个地址图片:src="staffPhoto" // 图片地址class="avatar"><i v-else // 没有的话,显示着地址图片class="el-icon-plus avatar-uploader-icon" /><el-progress v-show="showProgress" // 通过showProgress判断进度条是否显示type="line" // 进度条的显示形式:percentage="percent" // 进度条百分比显示class="progress" /></el-upload></div></template>
样式:
<style>.avatar-uploader .el-upload {border: 1px dashed #d9d9d9;border-radius: 6px;cursor: pointer;position: relative;overflow: hidden;}.avatar-uploader .el-upload:hover {border-color: #409eff;}.avatar-uploader-icon {font-size: 28px;color: #8c939d;width: 178px;height: 178px;line-height: 178px;text-align: center;}.avatar {width: 178px;height: 178px;display: block;}</style>
行为:
<script>import COS from 'cos-js-sdk-v5' const cos = new COS({SecretId: 'xxx', // 身份识别IDSecretKey: 'xxx' // 身份秘钥})console.log(cos)export default {name: 'Home',data () {return {imageUrl: '',percent: 0, // 进度条百分比showProgress: false, // 是否显示进度条staffPhoto: '' //图片地址}},methods: {handleAvatarSuccess (res, file) {this.imageUrl = URL.createObjectURL(file.raw)},beforeAvatarUpload (file) {const isJPG = file.type === 'image/jpeg'const isLt2M = file.size / 1024 / 1024 < 2if (!isJPG) {this.$message.error('上传头像图片只能是 JPG 格式!')}if (!isLt2M) {this.$message.error('上传头像图片大小不能超过 2MB!')}return isJPG && isLt2M},upload ({file }) {// console.log(params)this.showProgress = true // 显示进度条cos.putObject({Bucket: 'chucun-1305871078', /* 存储桶名字 hrsass-1255477649 */Region: 'ap-nanjing', /* 存储桶所在地域,必须字段 ap-beijing */Key: file.name, /* 文件名 */StorageClass: 'STANDARD', // 上传模式, 标准模式Body: file, // 上传文件对象onProgress: (progressData) => {this.percent = progressData.percent * 100 // 进度条显示百分比}}, (err, data) => {if (!err) {// 上传成功了console.log('上传成功了')setTimeout(() => {this.staffPhoto = `https://${data.Location}` // 图片地址// this.$emit('update:staffPhoto', `https://${data.Location}`)this.percent = 0 // 进度条恢复为0this.showProgress = false // 进度条隐藏}, 600)}})}}}</script>