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

相关推荐
计算机毕设指导610 小时前
基于微信小程序图像识别的智能垃圾分类系统【源码文末联系】
java·spring boot·mysql·微信小程序·小程序·分类·maven
lsyhaoshuai11 小时前
微信小程序开发实战:打造一款功能完善的随机决策工具--小转盘-拯救困难选择症
微信小程序·小程序·notepad++
项目題供诗13 小时前
微信小程序黑马优购(项目)(十)
微信小程序·小程序
计算机毕设指导613 小时前
基于Django的本地健康宝微信小程序系统【源码文末联系】
java·后端·python·mysql·微信小程序·小程序·django
说私域13 小时前
定制开发开源AI智能名片S2B2C商城小程序的产品经理职责与发展研究
人工智能·小程序·开源
小毅&Nora13 小时前
【人工智能】【阿里云百炼平台】 ① 大模型全景图:从文本到全模态,一张图看懂AI能力边界(2025版)
人工智能·阿里云·云计算
同聘云14 小时前
阿里云国际站gpu服务器能干什么?阿里云国际站gpu服务器怎么搭建?
服务器·阿里云·云计算
Kiyra1 天前
阿里云 OSS + STS:安全的文件上传方案
网络·人工智能·安全·阿里云·系统架构·云计算·json
一 乐1 天前
健身房预约|基于springboot + vue健身房预约小程序系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·学习·小程序
OC溥哥9991 天前
2D我的世界创造模式网页版正式出炉——《我们的2D创造世界:无限创意,多人同乐》欢迎来到ourcraft.xin网站上玩
后端·python·阿里云·flask·html·游戏程序