看了看阿里云官方文檔后簡單封裝了一下,方便以后使用
aliOssSts.js
/**
* 微信小程序通過STS直傳阿里云OSS
*(uniapp版上傳理朋,小程序原生需要將uni.XXX替換為wx.XXX)
*
* @param {filePath} 圖片臨時地址
* @param {option|Object} OSS和STS配置
* @param {savePath} oss中的文件目錄
* @param {AccessKeySecret} 服務(wù)端返回的STS中的AccessKeySecret
* @param {SecurityToken} 服務(wù)端返回的STS中的SecurityToken
* @param {AccessKeyId} 服務(wù)端返回的STS中的AccessKeyId
* @param {bucket} 存儲桶
* @param {area} 地區(qū)
* @return {string|boolean} 成功返回文件地址絮识,失敗返回false
*/
import crypto from 'crypto-js';
import {
Base64
} from 'js-base64/base64.js';
function upload(filePath, option = {
savePath,
AccessKeySecret,
SecurityToken,
AccessKeyId,
bucket,
area
}, callBack = () => {}) {
let fileType = filePath.split(".").pop();
let filename = option.savePath + "/" + createFileName(32) + "." + fileType;
const date = new Date();
date.setHours(date.getHours() + 1);
const policyText = {
expiration: date.toISOString(), // 設(shè)置policy過期時間。
conditions: [
["content-length-range", 0, 1024 * 1024 * 1024],
],
};
const policy = Base64.encode(JSON.stringify(policyText)) // policy必須為base64的string嗽上。
const signature = computeSignature(option.AccessKeySecret, policy)
const formData = {
OSSAccessKeyId: option.AccessKeyId,
signature,
policy,
'x-oss-security-token': option.SecurityToken,
key: filename,
success_action_status: 200
}
uni.uploadFile({
url: "https://" + option.bucket +
"." + option.area + ".aliyuncs.com",
filePath: filePath,
name: "file",
formData: formData,
success: (res) => {
let ossFileName = false;
if (res.statusCode === 200) {
console.log('上傳成功');
ossFileName = "https://" + option.bucket +
"." + option.area + ".aliyuncs.com/" +
filename;
}
callBack(ossFileName);
},
fail: err => {
console.log(err);
callBack(false);
}
})
}
// 簽名
function computeSignature(accessKeySecret, canonicalString) {
return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
}
// 生成隨機(jī)文件名
function createFileName(length) {
const data = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
];
let nums = "";
for (let i = 0; i < length; i++) {
const r = parseInt(Math.random() * 61, 10);
nums += data[r];
}
return nums;
}
export default {
upload
}
使用callback的方式獲取上傳結(jié)果
<script>
import AliOss from "@/存放路徑/aliOssSts.js";
export default {
data() {
return {
// OSS STS數(shù)據(jù)
ossData: [],
};
},
onLoad() {
// 向后端請求STS信息
this.getSts();
},
methods: {
getSts() {
let _this = this;
this.request.get(this.api.sts).then((res) => {
_this.ossData = res;
});
},
chooseImage() {
let _this = this;
uni.chooseImage({
count: 1,
sizeType: ["compressed", "camera"],
sourceType: ["album"],
success: function (res) {
if (res.errMsg == "chooseImage:ok") {
let filePath = res.tempFiles[0].path;
let option = {
savePath: "image",
AccessKeySecret: _this.ossData.AccessKeySecret,
SecurityToken: _this.ossData.SecurityToken,
AccessKeyId: _this.ossData.AccessKeyId,
bucket: _this.ossData.bucket,
area: "oss-cn-beijing",
};
AliOss.upload(filePath, option, function (res) {
if (res) {
console.log(res);
} else {
_this.Fun.tip("圖片上傳失敗,請稍后重試");
}
});
} else {
_this.Fun.tip("圖片選擇失敗");
}
},
});
},
},
};
</script>