1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
'use strict';
'use aliyun-oss-sign'
const Controller = require('egg').Controller;
const crypto = require("crypto")
const config = {
bucket: '', //oss桶名
region: '', //oss节点名
accessKeyId: '', //申请的osskey
accessKeySecret: '', // 申请的osssecret
callbackIp: "", // 回调ip,一定要能被外网访问的地址。
callbackPort: "8080", // 回调端口
callbackPath: "user/ossCallback", // 回调接口路径
expAfter: 60000, // 签名失效时间
maxSize: 1048576000 // 最大文件大小
}
class UserController extends Controller {
// 获取token
async getToken() {
const { ctx } = this;
const {
bucket,
region,
expAfter,
maxSize,
accessKeyId,
accessKeySecret,
callbackIp,
callbackPort,
callbackPath
} = config
let dict = this.ctx.request.body; // oss 文件夹 不存在会自动创建
const dirPath = dict.dirPath;
console.log(dirPath);
const host = `http://${bucket}.${region}.aliyuncs.com` //你的oss完整地址
const expireTime = new Date().getTime() + expAfter
console.log(expireTime);
const expiration = new Date(expireTime).toISOString()
console.log(expiration);
const policyString = JSON.stringify({
expiration,
conditions: [
['content-length-range', 0, maxSize],
['starts-with', '$key', dirPath]
]
})
const policy = Buffer(policyString).toString("base64")
const Signature = crypto.createHmac('sha1', accessKeySecret).update(policy).digest("base64")
const callbackBody = {
"callbackUrl": `http://${callbackIp}:${callbackPort}/${callbackPath}`,
"callbackHost": `${callbackIp}`,
"callbackBody": "{\"filename\": ${object},\"size\": ${size}}",
"callbackBodyType": "application/json"
}
const callback = Buffer(JSON.stringify(callbackBody)).toString('base64')
ctx.body = {
statusCode: "200",
message: 'oss签名成功',
result: {
Signature,
policy,
host,
'OSSAccessKeyId': accessKeyId,
'key': expireTime,
'success_action_status': 200,
dirPath,
callback
}
};
ctx.status = 200;
}
}
module.exports = UserController;
|