微信小程序上傳文件到阿里雲OSS的代碼


備注:我是使用STS臨時授權方式,則需要指定該項為SecurityToken的值,在formData中設置‘x-oss-security-token’,要不然會403報錯

uploadAliyun.ts

import './hmac.js';
import './sha1.js';
import Base64 from './Base64'; //Base64,hmac,sha1,crypto相關算法
//參考這里https://github.com/peterhuang007/weixinFileToaliyun.git
import Crypto from './crypto.js';

const clint = {
  rootDir: '', //默認存在根目錄,可根據需求改
  accessKeyId: '',
  accessKeySecret: '',
  stsToken: '',
  timeout: 87600, //這個是上傳文件時Policy的失效時間
};

export const uploadFile = (
  env: any,
  options: {
    file: any;
    dir: string;
    failCallback?: (arg0: Error) => void;
    successCallback?: (arg0: any) => void;
  }
) => {
  clint.rootDir = `https://${env.bucket}.${env.endpoint}`; //默認存在根目錄,可根據需求改
  clint.accessKeyId = env.accessKeyId;
  clint.accessKeySecret = env.accessKeySecret;
  clint.stsToken = env.stsToken;

  if (!options.file.path || options.file.path.length < 9) {
    wx.showModal({
      title: '圖片錯誤',
      content: '請重試',
      showCancel: false,
    });
    return;
  }

  let timestamp = new Date().getTime(); // 返回數值單位是毫秒
  const fileUrl = `${options.dir}/${timestamp}_${options.file.name}`; // dir表示要傳到這個目錄下
  const policyBase64 = getPolicyBase64();
  const signature = getSignature(policyBase64); //獲取簽名
  wx.uploadFile({
    url: clint.rootDir,
    filePath: options.file.path,
    name: 'file', //必須填file
    formData: {
      key: fileUrl,
      policy: policyBase64,
      signature: signature,
      OSSAccessKeyId: clint.accessKeyId,
      'x-oss-security-token': clint.stsToken, // 訪問是使用STS臨時授權,則需要指定該項為SecurityToken的值
      success_action_status: '200',
    },
    success: function (res) {
      if (res.statusCode != 200) {
        typeof options.failCallback === 'function' &&
          options.failCallback(new Error('上傳錯誤:' + JSON.stringify(res)));
        return;
      }
      // console.log('上傳圖片成功', res);
      typeof options.successCallback === 'function' &&
        options.successCallback(res);
    },
    fail: function (err) {
      typeof options.failCallback === 'function' && options.failCallback(err);
    },
  });
};

const getPolicyBase64 = function () {
  let date = new Date();
  date.setHours(date.getHours() + clint.timeout);
  let srcT = date.toISOString();
  const policyText = {
    expiration: srcT, // 設置該Policy的失效時間,超過這個失效時間之后,就沒有辦法通過這個policy上傳文件了
    conditions: [
      ['content-length-range', 0, 5 * 1024 * 1024], // 設置上傳文件的大小限制,5mb
    ],
  };
  const policyBase64 = Base64.encode(JSON.stringify(policyText));
  return policyBase64;
};

const getSignature = function (policyBase64: any) {
  const accessKey = clint.accessKeySecret;
  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accessKey, {
    asBytes: true,
  });
  const signature = Crypto.util.bytesToBase64(bytes);
  return signature;
};

頁面中調用

questions({
    method: 'POST',
    data: this.form,
}).then((res: any) = > {
    for (let file of this.fileUpload) {
        uploadFile(this.OssSign, {
            file: file,
            dir: 'iot',
            successCallback(res) {
                // console.log(res);
            },
        });
    }
    wx.switchTab({
        url: '/pages/question/index/main',
    });
});

 

參考鏈接:https://www.jianshu.com/p/34d6dcbdc2e5

官方文檔:https://help.aliyun.com/document_detail/31988.html?spm=5176.11065259.1996646101.searchclickresult.3ec33901vFANUq


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM