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

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

首先获取图片

javascript 复制代码
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

上传具体代码

javascript 复制代码
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();
          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 + "/" + t.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}/${t.getTime()}.${info.type}`)
              }
            },
            fail: res1 => {
              Taro.showToast({
                title: '上传失败,请重试',
                icon: 'error',
              })
            }
          })
        })
      }
    })
  })

}

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

相关推荐
吴声子夜歌2 天前
小程序——布局示例
小程序
luffy54592 天前
微信小程序页面使用类似filter函数的wxs语法
微信小程序·小程序
Slow菜鸟2 天前
微信小程序开发(二)目录结构完全指南
微信小程序·小程序
小扎仙森2 天前
关于阿里云实时语音翻译-Gummy推送WebSocket
websocket·阿里云·云计算
小小王app小程序开发2 天前
海外盲盒小程序抽赏玩法分析(附跨境技术落地要点)
小程序
一叶星殇2 天前
微信小程序请求拦截器踩坑:避免重复刷新 token
微信小程序·小程序
晚秋大魔王2 天前
ubutnu 服务器配置openclaw 使用阿里云百炼模型
运维·服务器·阿里云
hello kitty w2 天前
4. 基本语法
小程序
CHU7290352 天前
探索淘宝扭蛋机小程序:创意互动与趣味体验的融合
小程序
头发还在的女程序员2 天前
【免费下载】企业能源管理系统
小程序·策略模式·能源管理