如何使用腾讯云cos来封装头像组件

431 阅读1分钟

腾讯云cos申请配置

注册账号并实名认证

cloud.tencent.com/

开通对象存储

image.png

创建存储桶

image.png

设置cors规则

因为我们是在测试上传,全部允许上传就可以

image.png

image.png

配置云API密钥

找不到的话在这里搜索

image.png

image.png

封装组件

image.png

1 基本思路

image.png

2 封装 (完整代码)

上传腾讯云 安装依赖

npm i cos-js-sdk-v5 --save
<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :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="showProgress" :percentage="percent" />
    </el-upload>
  </div>
</template>
<script>
const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
  SecretId: 'xxx', // 身份识别ID
  SecretKey: 'xxx' // 身份秘钥
})
export default {
  name: 'UploadImg',
  props: {
    // 从父组件传递过来的v-model对应的值
    value: { type: String, default: '' }
  },
  data() {
    return {
      imageUrl: '',
      percent: 0,
      showProgress: false
    }
  },
  methods: {
    upload(res) {
      if (res.file) {
        this.showProgress = true
        // 执行上传操作
        cos.putObject({
          Bucket: 'xxx', /* 存储桶 */
          Region: 'xxx', /* 存储桶所在地域,必须字段 */
          Key: res.file.name, /* 文件名 */
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            this.percent = progressData.percent * 100
          }
        }, (err, data) => {
          this.showProgress = false
          console.log(err || data)
          // 上传成功之后
          if (data.statusCode === 200) {
            this.imageUrl = `https:${data.Location}`
            this.$emit('input', this.imageUrl)
          }
        })
      }
    }
  }
}
</script>

<style>
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  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>

</style>

3 局部代码

全局注册

...
import UploadImg from './UploadImg'
export default {
  install(Vue) {
    ...
    Vue.component('UploadImg', UploadImg)
  }
}

实例化cos对象

const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
  SecretId: 'xxx', // 身份识别ID
  SecretKey: 'xxx' // 身份秘钥
})

image.png

使用cos对象完成上传

 upload(res) {
      if (res.file) {
        this.showProgress = true
        // 执行上传操作
        cos.putObject({
          Bucket: 'xxx', /* 存储桶 */
          Region: 'xxx', /* 存储桶所在地域,必须字段 */
          Key: res.file.name, /* 文件名 */
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            this.percent = progressData.percent * 100
          }
        }, (err, data) => {
          this.showProgress = false
          console.log(err || data)
          // 上传成功之后
          if (data.statusCode === 200) {
            this.imageUrl = `https:${data.Location}`
            this.$emit('input', this.imageUrl)
          }
        })
      }
    }

image.png

进度条

image.png

<el-upload
  ...
+ <el-progress v-if="showProgress" :percentage="percent" />
</el-upload>

<style>
...
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background: #fff;
}
</style>

// 补充数据项
data () {
  return {
    // ...
    percent: 0,
    showProgress: false
  }
}

// 更新数据项值
upload(params) {
  if (params.file) {
    // 显示进度条
+    this.showProgress = true
    // 执行上传操作
    cos.putObject({
      Bucket: 'xxx', /* 存储桶 */
      Region: 'xxx', /* 存储桶所在地域,必须字段 */
      Key: params.file.name, /* 文件名 */
      StorageClass: 'STANDARD', // 上传模式, 标准模式
      Body: params.file, // 上传文件对象
      onProgress: (progressData) => {
        console.log(JSON.stringify(progressData))
+        this.percent = progressData.percent * 100
      }
    }, (err, data) => {
     // 隐藏进度条
+    this.showProgress = false
     ...
      }
    })
  }
}

4 组件使用

<el-form-item label="员工头像">
  <UploadImg v-model="userInfo.staffPhoto" />
</el-form-item>