Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
livehigh committed Oct 27, 2021
2 parents c516a9b + 4aaf55b commit 9eca5ee
Show file tree
Hide file tree
Showing 4 changed files with 146 additions and 13 deletions.
89 changes: 89 additions & 0 deletions demo/demo-post-policy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
var config = require('./config');

var uploadFile = function () {
// 请求用到的参数
// var prefix = 'https://cos.' + config.Region + '.myqcloud.com/' + config.Bucket + '/'; // 这个是后缀式,签名也要指定 Pathname: '/' + config.Bucket + '/'
var prefix = 'https://' + config.Bucket + '.cos.' + config.Region + '.myqcloud.com/';

// 对更多字符编码的 url encode 格式
var camSafeUrlEncode = function (str) {
return encodeURIComponent(str)
.replace(/!/g, '%21')
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')
.replace(/\*/g, '%2A');
};

// 获取临时密钥
var getCredentials = function (options, callback) {
wx.request({
method: 'GET',
url: 'http://127.0.0.1:3000/post-policy?key=' + encodeURIComponent(options.Key), // 服务端签名,参考 server 目录下的两个签名例子
dataType: 'json',
success: function (result) {
var data = result.data;
if (data) {
callback(data);
} else {
wx.showModal({title: '临时密钥获取失败', content: JSON.stringify(data), showCancel: false});
}
},
error: function (err) {
wx.showModal({title: '临时密钥获取失败', content: JSON.stringify(err), showCancel: false});
}
});
};

// 上传文件
var uploadFile = function (filePath) {
var Key = filePath.substr(filePath.lastIndexOf('/') + 1); // 这里指定上传的文件名
getCredentials({Key: Key}, function (credentials) {
var formData = {
'key': Key,
'success_action_status': 200,
'Content-Type': '',
'q-sign-algorithm': credentials.qSignAlgorithm,
'q-ak': credentials.qAk,
'q-key-time': credentials.qKeyTime,
'q-signature': credentials.qSignature,
'policy': credentials.policy,
};
if (credentials.securityToken) formData['x-cos-security-token'] = credentials.securityToken;
var requestTask = wx.uploadFile({
url: prefix,
name: 'file',
filePath: filePath,
formData: formData,
success: function (res) {
var url = prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/');
if (res.statusCode === 200) {
wx.showModal({title: '上传成功', content: url, showCancel: false});
} else {
wx.showModal({title: '上传失败', content: JSON.stringify(res), showCancel: false});
}
console.log(res.statusCode);
console.log(url);
},
fail: function (res) {
wx.showModal({title: '上传失败', content: JSON.stringify(res), showCancel: false});
}
});
requestTask.onProgressUpdate(function (res) {
console.log('正在进度:', res);
});
});
};

// 选择文件
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original'], // 可以指定是原图还是压缩图,这里默认用原图
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
uploadFile(res.tempFiles[0].path);
}
})
};

module.exports = uploadFile;
6 changes: 4 additions & 2 deletions demo/pages/index/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//index.js
var demoSdk = require('../../demo-sdk');
var demoNoSdk = require('../../demo-no-sdk');
var simpleUpload = require('../../demo-no-sdk');
var postUpload = require('../../demo-post-policy');

var option = {
data: {
Expand All @@ -15,7 +16,8 @@ for (var key in demoSdk) {
}
}

option.simpleUpload = demoNoSdk;
option.postUpload = postUpload;
option.simpleUpload = simpleUpload;

//获取应用实例
Page(option);
3 changes: 2 additions & 1 deletion demo/pages/index/index.wxml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
<view class="container">
<view class="title">不使用 SDK 简单上传例子(推荐)</view>
<view class="list">
<button type="primary" class="button" bindtap="simpleUpload"><text style="font-weight:bold;">[推荐]</text> 不使用 SDK 简单上传</button>
<button type="primary" class="button" bindtap="postUpload"><text style="font-weight:bold;">[推荐]</text> 不使用 SDK 简单上传1</button>
<button type="primary" class="button" bindtap="simpleUpload"><text style="font-weight:bold;">[推荐]</text> 不使用 SDK 简单上传2</button>
</view>
<view class="title">小程序完整 SDK 例子(功能齐全,文件较大)</view>
<view class="list">
Expand Down
61 changes: 51 additions & 10 deletions server/sts.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// 临时密钥服务例子
var STS = require('qcloud-cos-sts');
var bodyParser = require('body-parser');
var STS = require('qcloud-cos-sts');
var express = require('express');
var crypto = require('crypto');

// 配置参数
var config = {
Expand Down Expand Up @@ -52,9 +53,8 @@ app.all('/sts', function (req, res, next) {
'statement': [{
'action': config.allowActions,
'effect': 'allow',
'principal': {'qcs': ['*']},
'resource': [
'qcs::cos:ap-guangzhou:uid/' + AppId + ':prefix//' + AppId + '/' + ShortBucketName + '/' + config.allowPrefix,
'qcs::cos:' + config.region + ':uid/' + AppId + ':prefix//' + AppId + '/' + ShortBucketName + '/' + config.allowPrefix,
],
}],
};
Expand All @@ -63,12 +63,12 @@ app.all('/sts', function (req, res, next) {
secretId: config.secretId,
secretKey: config.secretKey,
proxy: config.proxy,
region: config.region,
durationSeconds: config.durationSeconds,
policy: policy,
}, function (err, tempKeys) {
var result = JSON.stringify(err || tempKeys) || '';
result.startTime = startTime;
res.send(result);
if (tempKeys) tempKeys.startTime = startTime;
res.send(err || tempKeys);
});
});

Expand Down Expand Up @@ -105,15 +105,56 @@ app.all('/sts', function (req, res, next) {
// durationSeconds: config.durationSeconds,
// policy: policy,
// }, function (err, tempKeys) {
// var result = JSON.stringify(err || tempKeys) || '';
// result.startTime = startTime;
// res.send(result);
// if (tempKeys) tempKeys.startTime = startTime;
// res.send(err || tempKeys);
// });
// });
//
// 用于 PostObject 签名保护
app.all('/post-policy', function (req, res, next) {
var query = req.query;
var now = Math.round(Date.now() / 1000);
var exp = now + 900;
var qKeyTime = now + ';' + exp;
var qSignAlgorithm = 'sha1';
var policy = JSON.stringify({
'expiration': new Date(exp * 1000).toISOString(),
'conditions': [
// {'acl': query.ACL},
// ['starts-with', '$Content-Type', 'image/'],
// ['starts-with', '$success_action_redirect', redirectUrl],
// ['eq', '$x-cos-server-side-encryption', 'AES256'],
{'q-sign-algorithm': qSignAlgorithm},
{'q-ak': config.secretId},
{'q-sign-time': qKeyTime},
{'bucket': config.bucket},
{'key': query.key},
]
});

// 签名算法说明文档:https://www.qcloud.com/document/product/436/7778
// 步骤一:生成 SignKey
var signKey = crypto.createHmac('sha1', config.secretKey).update(qKeyTime).digest('hex');

// 步骤二:生成 StringToSign
var stringToSign = crypto.createHash('sha1').update(policy).digest('hex');

// 步骤三:生成 Signature
var qSignature = crypto.createHmac('sha1', signKey).update(stringToSign).digest('hex');

console.log(policy);
res.send({
policyObj: JSON.parse(policy),
policy: Buffer.from(policy).toString('base64'),
qSignAlgorithm: qSignAlgorithm,
qAk: config.secretId,
qKeyTime: qKeyTime,
qSignature: qSignature,
// securityToken: securityToken, // 如果使用临时密钥,要返回在这个资源 sessionToken 的值
});
});

app.all('*', function (req, res, next) {
res.writeHead(404);
res.send({code: -1, message: '404 Not Found'});
});

Expand Down

0 comments on commit 9eca5ee

Please sign in to comment.