小程序+阿里Oss上传临时文件

4 篇文章 0 订阅
2 篇文章 0 订阅

以 Taro 框架为例(微信小程序可以直接将 Taro 替换为 wx)。

首先获取图片

Taro.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    success: (result) => {
      // 上传图片文件的具体代码
      useTaroUploadFile(result.tempFilePaths[0]).then(res=> {
        
      });
    },
    fail: res => {
      Taro.showToast({
        title: res.errMsg;
        icon: 'error',
       })
    }
  })

需要安装2个库

yarn add crypto-js 

yarn add js-base64

上传具体代码

export const useTaroUploadFile = (file) => {
  return new Promise((resolve, reject) => {
    // 需要获取文件的后缀,所以要调用该方法
    Taro.getImageInfo({
      src: file,
      success: info=>{
        // getSts:从后台获取上传所需要的参数,formData里面的参数可以全部由后台计算,部分也可以由前端计算
        getSts().then(res=> {
          const {bucketName, endpoint, dirPath, accessKeyId, securityToken, accessKeySecret} = res;
          const t = new Date();
          t.setHours(t.getHours() + 1);
          const timeNow = new Date();
          const policyText = {
            expiration: t.toISOString(), // 设置policy过期时间。
            conditions: [
              // 限制上传大小。
              ["content-length-range", 0, 1024 * 1024 * 1024],
            ],
          };
          const policy = Base64.encode(JSON.stringify(policyText));
          Taro.uploadFile({
            url: `https://${bucketName}.${endpoint}`,
            filePath: file,
            name: 'file',
            formData: {
              key: dirPath + "/" + timeNow.getTime() + '.' + info.type,
              policy: policy,
              OSSAccessKeyId: accessKeyId,
              signature: signature(policy, accessKeySecret),
              'x-oss-security-token': securityToken // 使用STS签名时必传。
            },
            success: uploadSuccess => {
              if (uploadSuccess.statusCode === 204){
                resolve(`https://${bucketName}.${endpoint}/${dirPath}/${timeNow.getTime()}.${info.type}`)
              }
            },
            fail: res1 => {
              Taro.showToast({
                title: '上传失败,请重试',
                icon: 'error',
              })
            }
          })
        })
      }
    })
  })

}

 其中,formData 的具体参数可以参考oss官方文档。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值