|
|
@@ -1,4 +1,5 @@
|
|
|
-import client from '@/utils/ali-oss';
|
|
|
+const OSS = require('ali-oss');
|
|
|
+import { restartProcess } from '@/api/index';
|
|
|
|
|
|
// 自定义请求头
|
|
|
const headers = {
|
|
|
@@ -32,12 +33,44 @@ const progress = (p, _checkpoint) => {
|
|
|
// 分片上传的断点信息。
|
|
|
console.log(_checkpoint);
|
|
|
};
|
|
|
+
|
|
|
+let credentials = null;
|
|
|
async function uploadAliOss(base64, filename) {
|
|
|
+ if (isCredentialsExpired(credentials)) {
|
|
|
+ // 获取 STS token.
|
|
|
+ const response = await restartProcess();
|
|
|
+ if (!response.ok) {
|
|
|
+ // 处理错误的HTTP状态码。
|
|
|
+ throw new Error(`获取STS令牌失败: ${response.status} ${response.statusText}`);
|
|
|
+ }
|
|
|
+ credentials = await response.json();
|
|
|
+ }
|
|
|
+ const client = new OSS({
|
|
|
+ region: 'cdn-svs-test.nipponpaint.com.cn',
|
|
|
+ // yourBucketName填写Bucket名称。
|
|
|
+ bucket: 'svs-test',
|
|
|
+ accessKeyId: credentials.AccessKeyId,
|
|
|
+ accessKeySecret: credentials.AccessKeySecret,
|
|
|
+ stsToken: credentials.SecurityToken,
|
|
|
+ });
|
|
|
+ let file = dataURLtoFile(base64, filename);
|
|
|
try {
|
|
|
- const result = await client.put(filename, new Buffer.from(base64), { headers });
|
|
|
+ const result = await client.put(filename, file, { headers });
|
|
|
console.log(result);
|
|
|
} catch (e) {
|
|
|
console.log(e);
|
|
|
}
|
|
|
}
|
|
|
+/**
|
|
|
+ * 判断临时凭证是否到期。
|
|
|
+ **/
|
|
|
+function isCredentialsExpired(credentials) {
|
|
|
+ if (!credentials) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ const expireDate = new Date(credentials.Expiration);
|
|
|
+ const now = new Date();
|
|
|
+ // 如果有效期不足一分钟,视为过期。
|
|
|
+ return expireDate.getTime() - now.getTime() <= 60000;
|
|
|
+}
|
|
|
export default uploadAliOss;
|