console
const app = tcb.init({
env: 'vue-douyin-test-16f173'
})
app
.auth({ persistance: "session" })
.anonymousAuthProvider()
.signIn()
.then(() => getTempCreFromCloudBase())
.catch(err => console.error(err))
function getUrl(Key) {
const Bucket = 'test-1259215285';
const Region = 'ap-nanjing';
const protocol = location.protocol === 'https:' ? 'https:' : 'http:';
const prefix = protocol + '//' + Bucket + '.cos.' + Region + '.myqcloud.com/';
var camSafeUrlEncode = function (str) {
return encodeURIComponent(str)
.replace(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/\*/g, '%2A');
};
return prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/');
}
function getTempCredential() {
return app.callFunction({
name: 'getTepCredential'
})
.then(res => {
return res.result.body.credentials
});
}
function upload(){
const ele = document.getElementById('f')
onUp(ele.files[0])
}
function getTempCreFromCloudBase() {
const DB = app.database()
return DB.collection('TempCredential')
.doc('latest')
.get()
.then(res => res.data[0])
}
async function onUp(filePath) {
try {
let tempCredential = await getTempCreFromCloudBase()
if( Date.now() + 5 * 60 * 1000 > tempCreFromDB.expiredTime * 1000 ) {
tempCredential = await getTempCredential()
}
console.log(tempCredential)
const Key = 'test/' + Date.now().toString() + ".jpg";
const headers = {
'x-cos-security-token': tempCredential.sessionToken,
'Authorization': CosAuth({
SecretId: tempCredential.tmpSecretId,
SecretKey: tempCredential.tmpSecretKey,
Method: "PUT",
Pathname: "/" + Key,
})
}
axios.put( getUrl(Key), filePath, { headers }).then(
res => console.log(res)
)
} catch(err) {
console.error(err)
}
}
<input type="file" id="f" onchange="upload()" />