準(zhǔn)備好配置文件 config.js
export const uploadImageUrl = 'https://+"桶名"+Endpoint/';//服務(wù)器域名
export const AK= 'AK'; //密鑰
export const SK = 'SK'; //密鑰
export const timeout = 87600; //超時(shí)時(shí)間
export const maxSize = 1024 * 1024 * 1024; //最大支持上傳的容量
export const PermissionPath = '路徑' //服務(wù)器上傳路徑
封裝上傳方法
const env = require("./config.js");
const Base64 = require("./js-base64.js"); //官方下載
const Crypto = require("./crypto-js.js");//官方下載
/**
* @param {*} options 自定義拓展參數(shù)
*/
const uploadFile = function (options) {
let {
filePath, // 文件地址
success,
progress,
fail
} = options;
// policy編碼計(jì)算方法
let getPolicyEncode = (policy) => {
// 傳入表單上傳的policy字段钦扭,對policy進(jìn)行Base64編碼
let encodedPolicy = Base64.encode(JSON.stringify(policy));
return encodedPolicy;
};
// 簽名計(jì)算方法
let getSignature = (policyEncoded, SecretKey) => {
// 利用SK對Base64編碼后的policy結(jié)果進(jìn)行HMAC-SHA1簽名計(jì)算
let bytes = Crypto.HmacSHA1(policyEncoded, SecretKey);
// 對計(jì)算結(jié)果進(jìn)行Base64編碼床绪,得到最終的簽名信息
let signature = Crypto.enc.Base64.stringify(bytes);
return signature;
};
//時(shí)間格式
let time = new Date();
let year = time.getFullYear();
let month = time.getMonth() + 1;
let day = time.getDate();
//路徑權(quán)限 + 項(xiàng)目code + '年/月/日'+ '隨機(jī)字符'
let projectCode = uni.getStorageSync('userInfo').projectCode;
// 文件保存名
let aliyunFileKey = env.PermissionPath + projectCode + `/${year}/${month}/${day}/` + uni.$u.guid(20) + '.aac';
// 設(shè)定policy內(nèi)容,policy規(guī)則定義可參考步驟1中的超鏈接簽名計(jì)算規(guī)則文檔
let date = new Date();
date.setHours(date.getHours() + env.timeout);
let OBSPolicy = {
"expiration": date.toISOString(),
"conditions": [
{ "bucket": "vd-asr" }, // 桶名要和配置文件中endpoint中的桶名保持一致
{ 'key': aliyunFileKey } // 很重要這一步 必須帶上
]
};
// 官方的方法調(diào)用
let policyEncoded = getPolicyEncode(OBSPolicy); // 計(jì)算base64編碼后的policy
let signature = getSignature(policyEncoded, env.OSSAccessKeyId); // 計(jì)算signature
// 發(fā)起請求
return new Promise( (resolve,reject) => {
uni.uploadFile({
url: env.uploadImageUrl,
name: 'file',
filePath: filePath,
header:{
'Content-Disposition':'attachment'
},
formData: {
'AccessKeyId': env.AccessKeySecret,
'policy': policyEncoded,
'signature': signature,
'key': aliyunFileKey
},
success: (res) => {
console.log("-----success------------------")
console.log('===== 上傳成功:', res);
resolve(env.uploadImageUrl+aliyunFileKey)
// 異步結(jié)束標(biāo)識
// resolve();
},
fail: (err) => {
console.log("-------fail----------------")
console.log(err)
reject(false)
},
});
});
};
module.exports = uploadFile; //導(dǎo)出方法