首先需要在项目中安装依赖
npm i cos-js-sdk-v5 --save
使用cos.putObject api完成上传的功能
// 下面的代码是固定写法
const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
SecretId: 'xxx', // 身份识别ID
SecretKey: 'xxx' // 身份秘钥
})
其中SecretId和SecretKey是创建存储桶配置API秘钥生成的
// 执行上传操作
cos.putObject(
{
Bucket: 'che-che-1307111563' /* 存储桶 */,
Region: 'ap-beijing' /* 存储桶所在地域,必须字段 */,
Key: res.file.name /* 文件名 */,
StorageClass: 'STANDARD', // 上传模式, 标准模式
Body: res.file, // 上传文件对象
// 设置上传的进度条
onProgress: progressData => {
console.log(JSON.stringify(progressData))
this.percent = progressData.percent * 100
}
},
(err, data) => {
// 隐藏进度条
this.showPrograss = false
console.log(err || data)
// 上传成功之后
if (data.statusCode === 200) {
const urlImg = `https://${data.Location}`
this.$emit('input', urlImg)
}
}
)
上传图片使用el-upload,上传进度条使用el-progress
<el-upload
class="avatar-uploader"
action="#"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:http-request="upload"
>
<img v-if="value" :src="value" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon" />
<el-progress v-if="showPrograss" type="circle" :percentage="percent" class="progress" />
</el-upload>