前期工作:需要在腾讯云注册一个账号,需要实名认证,到时候会用到里面的COS对象存储
下面是图片给大家展示操作:
如下:
创建完成后,需要吧地址记住,等会要用
前边配置挺多,耐心点
配置
下边是秘钥配置
可配置完了,开始复制代码吧
下载工具包:cos-js-sdk-v5
npm i cos-js-sdk-v5 --save 或者 yarn add cos-js-sdk-v5 --save
我们抽离出来一个组件专门做上传数据 我的组件名UploadImg
给你们一个地址:腾讯云对象存储操作说明
<template>
<div>
<el-upload
class="avatar-uploader"
action="#"
:show-file-list="false"
:before-upload="beforeAvatarUpload"
:http-request="upload"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<div v-else>
<i class="el-icon-plus avatar-uploader-icon" />
<el-progress type="circle" :percentage="66" class="progress" />
</div>
</el-upload>
</div>
</template>
<script>
const COS = require('cos-js-sdk-v5')
const cos = new COS({
SecretId: 'xxxxxxx', // 身份识别ID
SecretKey: 'xxxxxxx' // 身份秘钥
})
export default {
data() {
return {
imageUrl: ''
}
},
methods: {
upload(res) {
if (res.file) {
// 执行上传操作
cos.putObject({
Bucket: 'xxxxx', /* 存储桶 */
Region: 'xxxxx', /* 存储桶所在地域,必须字段 */
Key: res.file.name, /* 文件名 */
StorageClass: 'STANDARD', // 上传模式, 标准模式
Body: res.file, // 上传文件对象;
onProgress: (progressData) => {
console.log(JSON.stringify(progressData))
}
}, (err, data) => {
console.log(err || data)
// 上传成功之后
if (data.statusCode === 200) {
this.imageUrl = `https:${data.Location}`
}
})
}
},
beforeAvatarUpload(file) {
const isPNG = file.type === 'image/png'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isPNG) {
this.$message.error('上传头像图片只能是 PNG 格式!')
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
}
return isPNG && isLt2M
}
}
}
</script>
<style lang="scss" scoped>
.progress {
position: absolute;
display: flex;
top: 50%;
left: 25%;
transform: translate(-50%,-50%);
background: #fff;
}
.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>
上面代码不熟悉的地方,下边这个截图有点紧凑,好好看看
应就这些,还有不懂的问题可以讨论