42 lines
1.8 KiB
JavaScript
42 lines
1.8 KiB
JavaScript
import config from '@/config'
|
||
const COS = require('./cos-wx-sdk-v5.js'); // 开发时使用
|
||
// const COS = require('./lib/cos-wx-sdk-v5.min.js'); // 上线时使用压缩包
|
||
|
||
const baseUrl = config.baseUrl
|
||
|
||
const cos = new COS({
|
||
SimpleUploadMethod: 'putObject', // 强烈建议,高级上传、批量上传内部对小文件做简单上传时使用putObject,sdk版本至少需要v1.3.0
|
||
getAuthorization: function(options, callback) {
|
||
// 初始化时不会调用,只有调用 cos 方法(例如 cos.putObject)时才会进入
|
||
// 异步获取临时密钥
|
||
// 服务端 JS 示例:https://github.com/tencentyun/cos-js-sdk-v5/blob/master/server/
|
||
// 服务端其他语言参考 COS STS SDK :https://github.com/tencentyun/qcloud-cos-sts-sdk
|
||
// STS 详细文档指引看:https://cloud.tencent.com/document/product/436/14048
|
||
const stsUrl = baseUrl + '/cos/sts'; // stsUrl 替换成您自己的后端服务
|
||
wx.request({
|
||
url: stsUrl,
|
||
data: {
|
||
bucket: options.Bucket,
|
||
region: options.Region,
|
||
},
|
||
dataType: 'json',
|
||
success: function(result) {
|
||
const data = result.data;
|
||
const credentials = data && data.credentials;
|
||
if (!data || !credentials) return console.error('credentials invalid');
|
||
// 检查 credentials 格式
|
||
console.log(credentials);
|
||
callback({
|
||
TmpSecretId: credentials.tmpSecretId,
|
||
TmpSecretKey: credentials.tmpSecretKey,
|
||
// v1.2.0之前版本的 SDK 使用 XCosSecurityToken 而不是 SecurityToken
|
||
SecurityToken: credentials.sessionToken,
|
||
// 建议返回服务器时间作为签名的开始时间,避免用户浏览器本地时间偏差过大导致签名错误
|
||
StartTime: data.startTime, // 时间戳,单位秒,如:1580000000
|
||
ExpiredTime: data.expiredTime, // 时间戳,单位秒,如:1580000900
|
||
});
|
||
}
|
||
});
|
||
}
|
||
});
|
||
export default cos; |