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

相关推荐
2501_9159184115 小时前
iOS 上架全流程指南 iOS 应用发布步骤、App Store 上架流程、uni-app 打包上传 ipa 与审核实战经验分享
android·ios·小程序·uni-app·cocoa·iphone·webview
00后程序员张17 小时前
iOS App 混淆与加固对比 源码混淆与ipa文件混淆的区别、iOS代码保护与应用安全场景最佳实践
android·安全·ios·小程序·uni-app·iphone·webview
破无差1 天前
《赛事报名系统小程序》
小程序·html·uniapp
00后程序员张1 天前
详细解析苹果iOS应用上架到App Store的完整步骤与指南
android·ios·小程序·https·uni-app·iphone·webview
海绵宝宝不喜欢侬1 天前
uniapp-微信小程序分享功能-onShareAppMessage
微信小程序·小程序·uni-app
2501_915106321 天前
Xcode 上传 ipa 全流程详解 App Store 上架流程、uni-app 生成 ipa 文件上传与审核指南
android·macos·ios·小程序·uni-app·iphone·xcode
亮子AI1 天前
【小程序】微信小程序隐私协议
微信小程序·小程序
weixin_177297220691 天前
短剧小程序系统开发:打造个性化娱乐新平台
小程序·娱乐·短剧
weixin_lynhgworld1 天前
剧本杀小程序系统开发:开启沉浸式社交娱乐新纪元
小程序·娱乐
~废弃回忆 �༄1 天前
mobx-miniprogram小程序的数据传输
小程序