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

相关推荐
XMYX-03 小时前
Ubuntu 22.04.5 LTS 安装 Docker 29.1.5(阿里云镜像,生产环境实战)
ubuntu·阿里云·docker
CRMEB系统商城4 小时前
CRMEB多商户系统(PHP)- 移动端二开之基本容器组件使用
运维·开发语言·小程序·php
猿码优创5 小时前
过滤境外ip和域名访问的解决方案
网络·网络协议·tcp/ip·安全·阿里云
阿也在北京6 小时前
基于Neo4j和TuGraph的知识图谱与问答系统搭建——胡歌的导演演员人际圈
python·阿里云·知识图谱·neo4j
沉默-_-7 小时前
微信小程序网络请求 wx.request 详解
网络·学习·微信小程序·小程序
DashVector8 小时前
通义深度搜索-上传文件
人工智能·深度学习·阿里云·ai·深度优先
2501_915909069 小时前
设置了 SSL Pinning 与双向 TLS 验证要怎么抓包
网络·网络协议·ios·小程序·uni-app·iphone·ssl
阿里云云原生9 小时前
阿里云全新发布的 UModel 是什么
人工智能·阿里云·云计算·可观测·umodel
溜达的大象9 小时前
Navidrome 打造专属无损音乐库,加载cpolar局域网外访问也能超丝滑
阿里云·docker·云原生·eureka
龙兵科技小付说13 小时前
不同价格的上门做饭小程序APP都有什么功能?
小程序·软件开发·上门做饭