uniapp小程序上传oss

uniapp上传小程序代码

javascript 复制代码
import crypto from 'crypto-js';
import { Base64 } from 'js-base64/base64.js';
// 计算oss签名。
function computeSignature(accessKeySecret, canonicalString) {
  return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
}
const getPolicyBase64 = function () {
  let date = new Date();
  date.setHours(date.getHours() + '87600');
  let expiration = date.toISOString();
  const policyText = {
    "expiration": expiration, //设置该Policy的失效时间
    "conditions": [
      ["content-length-range", 0, 1024 * 1024 * 1024 * 5] // 设置上传文件的大小限制, 5G
    ]
  };
  const policyBase64 = Base64.encode(JSON.stringify(policyText));
  return policyBase64;
}

/**
 * 获取oss签名
 */
export const getOssAuthorization = (callback) => {
  request({
    url: `xxxxx`,
    method: 'get',
  }).then((res) => {
  	// 返回参数
	// {
    //   accessKeyId: "",
    //   accessKeySecret: "",
    //   bucket: '',
    //   bucketName: "", 桶名
    //   callback: null,
    //   dir: "",
    //   endpoint: "https://oss-cn-xxxx.aliyuncs.com",
    //   keyName: "",
    //   osBasicInfo: "",
    //   path: '',
    //   region: "",
    //   response: '',
    //   securityToken: ''
    // }
    callback && callback(res.data)
  })
};
/**
 * 
 * @param {string} filePath 文件的路径
 * @param {string} fileSize 文件的大小
 * @param {string} fileSuffix 文件后后缀
 * @param {string} fileName 文件夹名
 * @param {*} param
 * @returns 
 */
export const ossUploadFile = (filePath, fileSize, fileSuffix = '', fileName) => {
  return new Promise((resolve, reject) => {
    if (!filePath) {
      uni.showModal({ title: '文件错误', content: '请重试', showCancel: false });
      uni.hideLoading();
      return false;
    }
    getOssAuthorization(async(data) => {
      // 这里指定上传的文件名
      const aliyunFileKey = `${data.dir}${fileName}`;
      // 拼接上传的oss地址
      let str = 'https://'
      const aliyunServerURL = data.endpoint.replace(str, `${str}${data.bucketName}.`);
      // 密钥
      const accessKeyId = data.accessKeyId;
      // 超时的时间
      const policyBase64 = getPolicyBase64();
      // 临时证书
      const signature = computeSignature(data.accessKeySecret, policyBase64);
      uni.uploadFile({
        url: aliyunServerURL, // 上传的域名
        filePath: filePath, // 上传的文件
        name: "file",
        formData: {
          key: aliyunFileKey, // 文件名称
          policy: policyBase64, // 过期时间
          OSSAccessKeyId: accessKeyId, // 秘钥
          signature: signature, // 临时证书
          success_action_status: "200",
          "x-oss-security-token": data.securityToken
        },
        success: (res) => {
          console.log("成功回调", res)
          if (res.statusCode == 200) {
            let result = aliyunServerURL + "/" + aliyunFileKey
            console.log(result, '====文件地址');
            resolve(result)
          } else {
            reject(res)
          }
        },
        fail: (err) => {
          console.log(err, 'err==上传失败');
          err.wxaddinfo = aliyunServerURL
          reject(err)
        },
      })
    })
  });
}
相关推荐
计算机学姐10 分钟前
基于微信小程序的调查问卷管理系统
java·vue.js·spring boot·mysql·微信小程序·小程序·mybatis
正小安7 小时前
如何在微信小程序中实现分包加载和预下载
前端·微信小程序·小程序
说私域7 小时前
基于定制开发与2+1链动模式的商城小程序搭建策略
大数据·小程序
二十雨辰10 小时前
[uni-app]小兔鲜-07订单+支付
uni-app
工业互联网专业14 小时前
毕业设计选题:基于ssm+vue+uniapp的校园水电费管理小程序
vue.js·小程序·uni-app·毕业设计·ssm·源码·课程设计
说私域18 小时前
社群团购中的用户黏性价值:以开源小程序多商户AI智能名片商城源码为例
人工智能·小程序
以对_1 天前
uview表单校验不生效问题
前端·uni-app
迷雾yx1 天前
开发微信小程序 基础02
微信小程序·小程序
迷雾yx1 天前
开发微信小程序 基础03
微信小程序·小程序
说私域1 天前
地理定位营销与开源AI智能名片O2O商城小程序的融合与发展
人工智能·小程序