微信小程序上传腾讯云COS

操作

pnpm i cos-wx-sdk-v5

封装代码

import { cosSts } from '@/service/common'
import COS from 'cos-wx-sdk-v5'

export default function useUpload2<T = string>(formData: Record<string, any> = {}) {
  const loading = ref(false)
  const error = ref(false)
  const data = ref<T>()
  const run = () => {
    // #ifdef MP-WEIXIN
    // 微信小程序从基础库 2.21.0 开始, wx.chooseImage 停止维护,请使用 uni.chooseMedia 代替。
    // 微信小程序在2023年10月17日之后,使用本API需要配置隐私协议
    uni.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: (res) => {
        loading.value = true
        const file = res.tempFiles[0]
        uploadFile<T>({ file, formData, data, error, loading })
      },
      fail: (err) => {
        error.value = true
      },
    })
    // #endif
    // #ifndef MP-WEIXIN
    uni.chooseImage({
      count: 1,
      success: (res) => {
        loading.value = true
        const file = res.tempFilePaths[0]
        uploadFile<T>({ file, formData, data, error, loading })
      },
      fail: (err) => {
        error.value = true
      },
    })
    // #endif
  }

  return { loading, error, data, run }
}

function uploadFile<T>({ file, formData, data, error, loading }) {
// cosSts 服务端接口需要返回:上传的存储桶、地域、随机路径的对象键、临时密钥 等
  cosSts().then((res) => {
    const {
      bucketName,
      regionName,
      startTime,
      expiredTime,
      tmpSecretId,
      tmpSecretKey,
      sessionToken,
    } = res.data
    const cos = new COS({
      SecretId: tmpSecretId,
      SecretKey: tmpSecretKey,
      SecurityToken: sessionToken,
      StartTime: startTime,
      ExpiredTime: expiredTime,
      SimpleUploadMethod: 'putObject',
    })

    cos
      .uploadFile({
        Bucket: bucketName,
        Region: regionName,
        Key: Date.now() + '.jpg',
        FilePath: file.tempFilePath,
        FileSize: file.size,
      })
      .then((res) => {
        data.value = res.Location
      })
      .catch(() => {
        error.value = true
      })
      .finally(() => {
        loading.value = false
      })
  })
}

参考链接

上传对象实践教程