微信小程序直接上传文件到腾讯云

106 阅读1分钟

对象存储 小程序 SDK 快速入门_腾讯云

因为使用的是uni-app开发小程序,所有编写了一个hook

// import COS from 'cos-wx-sdk-v5'

// 采用下面的方式是为了分包
// @ts-ignore
const COS = require('../cos-wx-sdk-v5.min.js')


type ICosInstance = () => {
  cos: any,
  uploadFileCos: (file: UniApp.MediaFile) => Promise<string>
}

/**
 * COS 配置数据
 */
let config: any = {}

const getAuthorization = async () => {
  const res = await ajax('POST', '/get-credential', {
    credentialDurationSeconds: 120,
    credentialForAction: 'UPLOAD',
  })

  config = res?.config || {}

  return res?.data || {}
}


const useCosInstance: ICosInstance = () => {

  onMounted(async () => {
    await getAuthorization()
  })

  const cos = new COS({
    // SecretId: SecretId,
    // SecretKey: SecretKey,
    getAuthorization: async (options: any, callback: any) => {
      console.log('--getAuthorization--', options, callback)
      const res = await getAuthorization()

      callback({
        TmpSecretId: res?.tmpSecretId,
        TmpSecretKey: res?.tmpSecretKey,
        // v1.2.0之前版本的 SDK 使用 XCosSecurityToken 而不是 SecurityToken
        SecurityToken: res?.sessionToken,
        // 建议返回服务器时间作为签名的开始时间,避免用户浏览器本地时间偏差过大导致签名错误
        StartTime: res?.startTime, // 时间戳,单位秒,如:1580000000
        ExpiredTime: res?.expiredTime, // 时间戳,单位秒,如:1580000900
      });

    }
  })

  const uploadFileCos = (file: UniApp.MediaFile) => {

    console.log(`【uploadFileCos】`, '上传文件', file)

    const id = Date.now()

    return new Promise<string>((resolve, reject) => {
      cos.uploadFile({
        Bucket: config.bucketName, /* 填写自己的 bucket,必须字段 */
        Region: config.region,     /* 存储桶所在地域,必须字段 */
        Key: [
          configuration.objectKeyPrefix,
          globalData.openId,
          dayjs().format('YYYYMMDD'),
          Date.now() + '.' + file.tempFilePath.split('.').slice(-1)
        ].join('/'),              /* 存储在桶里的对象键(例如1.jpg,a/b/test.txt),必须字段 */
        FilePath: file.tempFilePath,
        FileSize: file.size,
        SliceSize: 1024 * 1024 * 5,     /* 触发分块上传的阈值,超过5MB 使用分块上传,小于5MB使用简单上传。可自行设置,非必须 */
        onProgress: function (progressData: any) {
          console.log('上传进度', JSON.stringify(progressData));
        }
      }).then((data: any) => {
        console.log(`【uploadFileCos ✔️】${Date.now() - id}ms`, '【🍎入参:】', file, '【🍐出参:】', data)

        resolve(config.accessDomain + data.Location.split('/').slice(1).join('/'))

      }).catch((err: any) => {
        console.log(`【uploadFileCos ❌】${Date.now() - id}ms`, '【🍎入参:】', file, '【🍐出参:】', err)

        uni.showToast({
          title: '上传失败',
          icon: 'error',
        })

        reject(err)
      })
    })
  }


  return {
    cos,
    uploadFileCos,
  }
}

export default useCosInstance

如果不想使用腾讯云SDK推荐使用 对象存储 小程序直传实践_腾讯云方法