小程序+阿里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官方文档。

相关推荐
weixin_lynhgworld15 小时前
盲盒抽谷机小程序系统开发:从0到1的完整方法论
小程序
weixin_lynhgworld15 小时前
短剧小程序系统开发:赋能创作者,推动短剧艺术创新发展
小程序
是乐谷15 小时前
阿里云杭州 AI 产品法务岗位信息分享(2025 年 8 月)
java·人工智能·阿里云·面试·职场和发展·机器人·云计算
一匹电信狗18 小时前
【C++】异常详解(万字解读)
服务器·c++·算法·leetcode·小程序·stl·visual studio
玩转以太网19 小时前
3 种方式玩转网络继电器!W55MH32 实现网页 + 阿里云 + 本地控制互通
网络·物联网·阿里云
说私域1 天前
基于开源AI智能客服、AI智能名片与S2B2C商城小程序的微商服务优化及复购转介绍提升策略研究
人工智能·小程序
熬耶2 天前
Uniapp之微信小程序自定义底部导航栏形态
微信小程序·小程序·uni-app
IT毕设实战小研2 天前
基于Spring Boot校园二手交易平台系统设计与实现 二手交易系统 交易平台小程序
java·数据库·vue.js·spring boot·后端·小程序·课程设计
weixin_177297220692 天前
剧本杀小程序系统开发:重构推理娱乐生态
小程序·重构·娱乐
IT毕设实战小研2 天前
基于SpringBoot的救援物资管理系统 受灾应急物资管理系统 物资管理小程序
java·开发语言·vue.js·spring boot·小程序·毕业设计·课程设计