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

相关推荐
我很苦涩的4 小时前
使用微信小程序实现多格验证码效果
微信小程序·小程序
阿里花盘4 小时前
花店微信小程序怎么做,创建一个小程序需要多少钱
微信小程序·小程序
2501_916008894 小时前
没有源码如何加密 IPA 实战流程与多工具组合落地指南
android·ios·小程序·https·uni-app·iphone·webview
LXA08096 小时前
UniApp 小程序中使用地图组件
小程序·uni-app·notepad++
阿里云云原生7 小时前
阿里云 FunctionAI 技术详解:基于 Serverless 的企业级 AI 原生应用基础设施构建
人工智能·阿里云·serverless
bug总结7 小时前
更新原生小程序封装(新增缓存订阅)完美解决
前端·缓存·小程序
竹君子7 小时前
研发管理知识库(13)阿里云的DevOps工具介绍
阿里云·云计算·devops
2501_9159090612 小时前
Flutter 应用怎么加固,多工具组合的工程化实战(Flutter 加固/Dart 混淆/IPA 成品加固/Ipa Guard + CI)
android·flutter·ios·ci/cd·小程序·uni-app·iphone
程思扬15 小时前
开源 + 实时 + 无网络限制:Excalidraw 是流程图协作新选择
网络·人工智能·阿里云·ai·开源·流程图
2501_9159090616 小时前
深入理解HTTPS和HTTP的区别、工作原理及安全重要性
安全·http·ios·小程序·https·uni-app·iphone