Files
ClassContent/历届学生/front-end-team-11/项目开发/上课项目/nodejs博客/backendv2/src/utils/aliyunOss.ts
2024-09-27 02:06:13 +08:00

53 lines
1.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import crypto from "crypto-js";
export class uploadOssHelper {
accessKeyId: string = "";
accessKeySecret: string = "";
timeout: number;
maxSize: number;
constructor(options: {
accessKeyId: string,
accessKeySecret: string,
timeout?: number,
maxSize?: number
}) {
this.accessKeyId = options.accessKeyId;
this.accessKeySecret = options.accessKeySecret;
// 限制参数的生效时间,单位为小时,默认值为1。
this.timeout = options.timeout || 1;
// 限制上传文件的大小,单位为MB,默认值为10。
this.maxSize = options.maxSize || 10;
}
createUploadParams() {
const policy = this.getPolicyBase64();
const signature = this.signature(policy);
return {
OSSAccessKeyId: this.accessKeyId,
policy: policy,
Signature: signature,
};
}
getPolicyBase64() {
let date = new Date();
// 设置policy过期时间。
date.setHours(date.getHours() + this.timeout);
let srcT = date.toISOString();
const policyText = {
expiration: srcT,
conditions: [
// 限制上传文件大小。
["content-length-range", 0, this.maxSize * 1024 * 1024],
],
};
const buffer = new Buffer(JSON.stringify(policyText));
return buffer.toString("base64");
}
signature(policy: string) {
return crypto.enc.Base64.stringify(
crypto.HmacSHA1(policy, this.accessKeySecret)
);
}
}