vue base64图片上传到腾讯云cos

vue yekong 132℃

使用

js vue base64文件转file

代码

生成微信小程序码,base64转为file上传到腾讯云cos

/**
* @Author: 858834013@qq.com
* @Name: qrCode
* @Date: 2022-05-17
* @Desc: 生成二维码
*/
<template>
  <div>
    <div @click="getShow">
      <slot></slot>
    </div>
  </div>
</template>

<script>

import { editAdminRole, getUn, qpCode } from '@/api/user'
import configs from '@/config/config'
import { uuid } from 'vue-uuid'
import base64ToBlob, { getFileName } from '@/utils/auth'

const COS = require('cos-js-sdk-v5')
const Bucket = configs.Bucket
const Region = configs.Region
const cos = new COS({
  SecretId: configs.SecretId,
  SecretKey: configs.SecretKey
})
export default {
  name: 'changeRole',
  components: {},
  props: {
    id: {
      type: String | Number,
      default() {
        return ''
      }
    }
  },
  data() {
    return {
      show: false,
      img: ''
    }
  },
  watch: {
    show() {
      if (this.show) {
        this.getUn()
      }
    }
  },
  mounted() {
  },
  methods: {
    getHide() {
      this.show = false
    },
    getShow() {
      this.show = true
    },
    /**上传图片到腾讯云**/
    uploadFileToTencentClound(file) {
      console.log(file)
      console.log('文件名')
      return new Promise(resolve => {
        cos.putObject(
          {
            Bucket: Bucket /* 存储桶 */,
            Region: Region /* 存储桶所在地域,必须字段 */,
            Key: uuid.v1() + '.png' /* 文件名 */,
            StorageClass: 'STANDARD', // 上传模式, 标准模式
            Body: file, // 上传文件对象
            onProgress: function(info) {
              console.log('[cos.postObject-seccess]', JSON.stringify(info))
            }
          },
          function(err, data) {
            console.log('[cos.postObject-err]', err || data)
            resolve(data.Location)
          }
        )
      })
    },
    //生成小程序码
    getUn() {
      var that = this
      let params = {
        'page': 'pages/home/home',
        'scene': this.id,
        'width': '200'
      }
      getUn(params).then(function(res) {
        if (res.code == 200) {
          that.img = 'data:image/png;base64,' + res.data.img
          // 上传图片到腾讯cos
          that.uploadFileToTencentClound(base64ToBlob(that.img)).then(response => {
            that.qpCode('https://' + response)
          })
        } else {
          console.log('查询失败')
        }
      })
    },
    //保存图片地址
    qpCode(url) {
      var that = this
      qpCode({
        'qpCode': url,
        'userId': that.id
      }).then(function(res) {
        if (res.code == 200) {
          that.$emit('getdata', 0)
        } else {
          console.log('查询失败')
        }
      })
    },
  }
}
</script>

喜欢 (0)