以下為封裝的js文件,上傳時(shí)引入該文件,調(diào)用uploadFile方法傳入圖片臨時(shí)地址,callback中接收上傳后的網(wǎng)絡(luò)地址;
(js的sdk的使用方式基本和小程序的差不多,不過上傳后的訪問地址不是callback返回的,而是需要自己根據(jù)前綴和圖片名手動(dòng)拼接)
const app = getApp();
const { $req } = require('./request.js'); // $req方法為對(duì)微信request方法的封裝,這里就不過多贅述了
const COS = require('../static/js/cos-wx-sdk-v5-min.js'); // 引入sdk
const Bucket = 'xxx-11111111'; // 這里填你存儲(chǔ)桶名稱
const Region = 'ap-beijing'; // 填你的地域名稱
const cos = new COS({
getAuthorization: function (options, callback) {
// 異步獲取簽名
$req({
url: 'xxx', // 后端簽名接口
method: 'POST',
success(result) {
console.log(result);
let data = result.data.data;
let credentials = data.credentials;
callback({
TmpSecretId: credentials.tmpSecretId,
TmpSecretKey: credentials.tmpSecretKey,
XCosSecurityToken: credentials.sessionToken,
ExpiredTime: data.expiredTime, // SDK 在 ExpiredTime 時(shí)間前,不會(huì)再次調(diào)用 getAuthorization
});
}
})
}
});
// 上傳文件
const uploadFile = (filePath, callback) => {
let filename = filePath.substr(filePath.lastIndexOf('/') + 1);
cos.postObject({
Bucket: Bucket,
Region: Region,
Key: filename,
FilePath: filePath,
onProgress: info => {
console.log(JSON.stringify(info));
}
}, (err, data) => {
if (err === null) {
callback(data);
} else {
wx.hideLoading();
wx.showToast({
title: '上傳失敗',
icon: 'none'
})
}
});
}
module.exports = {
uploadFile,
}