ant-design-vue的Upload 上传怎么用腾讯云的cos

安装依赖npm i cos-js-sdk-v5 --save

封装工具类

const COS = require('cos-js-sdk-v5')
var cos = new COS({
  SecretId: '', // 用户id
  SecretKey: '' // 用户密钥
})

const httpUploadRequest = (res) => {
  return new Promise((resolve, reject) => {
    const paths = res.file.name.split('.')
    const suffix = '.' + paths[paths.length - 1]
    const filename = guid() + suffix
    cos.putObject(
      {
        Bucket: 'ssb-1307150208', // 必须:存储桶
        Region: 'ap-shanghai', // 存储桶所在地域,必须字段,
        Key: '/' + filename, // 必须 :目录/文件名
        Body: res.file, // 上传文件对象
        onProgress: function (progressData) {
          // 进度条
          console.log(JSON.stringify(progressData))
        }
      },
      (err, data) => {
        console.log(data)
        if (data.statusCode == 200) {
          resolve(data)
        } else {
          reject(err)
        }
      }
    )
  })
}

function guid() {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
  }
  return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() +        S4()
}

export default httpUploadRequest
<template>
 <a-upload
   name="avatar"
   list-type="picture-card"
   class="avatar-uploader"
   action="#"
   :show-upload-list="false"
   :before-upload="beforeUpload"
   :customRequest="httpUpload"
 >
   <img v-if="imageUrl" :src="imageUrl" alt="avatar" class="image-size" />
   <div v-else>
      <a-icon :type="loading ? 'loading' : 'plus'" />
      <div class="ant-upload-text">上传二维码</div>
   </div>
 </a-upload>
</template>

<script>
import httpUploadRequest from '@/utils/cos-upload'
export default {
  data() {
    return {
      loading: false,
      imageUrl: ''
    }
  },
  methods: {
    httpUpload(res) {
      this.loading = true
      httpUploadRequest(res)
        .then((result) => {
          this.imageUrl = `https://${result.Location}`
          this.loading = false
        })
        .catch(() => {
          this.$message.error('上传失败,请稍后再试。')
          this.loading = false
        })
    },

    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('只能上传jpg或png格式的图片。')
      }
      return isJpgOrPng
    }
  }
}
</script>

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值