初始化
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
|
||||
const computeSignature = (accessKeySecret, canonicalString) => {
|
||||
return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
|
||||
}
|
||||
|
||||
export async function uploadOssByPath(filePath) {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
const date = new Date();
|
||||
date.setMinutes(date.getMinutes() + 1);
|
||||
const policyText = {
|
||||
expiration: date.toISOString(), // 设置policy过期时间。
|
||||
conditions: [
|
||||
// 限制上传大小。
|
||||
["content-length-range", 0, 1024 * 1024 * 1024],
|
||||
],
|
||||
};
|
||||
let sts = uni.getStorageSync('sts');
|
||||
let stsExpired = uni.getStorageSync('stsExpiredAt');
|
||||
if(!sts || (stsExpired && dayjs().isBefore(dayjs(stsExpired)))){
|
||||
const {data: {data: {credentials}}} = await request.get(`${SERVER_API_URL}/oss/getSTSToken`)
|
||||
uni.setStorageSync('sts', credentials)
|
||||
uni.setStorageSync('stsExpiredAt', credentials.expiration)
|
||||
sts = credentials
|
||||
}
|
||||
console.log(sts)
|
||||
const [filename, ext] = filePath.split('.')
|
||||
const key = `headers/${md5(filename + (Math.random() * 100000))}.${ext}`
|
||||
const policy = Base64.encode(JSON.stringify(policyText))
|
||||
const signature = computeSignature(sts.accessKeySecret, policy)
|
||||
uni.uploadFile({
|
||||
url: 'https://oss.wsdns.cn',
|
||||
name: 'file',
|
||||
filePath,
|
||||
formData: {
|
||||
key,
|
||||
policy,
|
||||
OSSAccessKeyId: sts.accessKeyId,
|
||||
signature,
|
||||
'x-oss-security-token': sts.securityToken
|
||||
},
|
||||
success: () => {
|
||||
resolve(`https://oss.wsdns.cn/${key}`)
|
||||
},
|
||||
error: (err) => reject(err)
|
||||
})
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user