96 lines
3.5 KiB
JavaScript
96 lines
3.5 KiB
JavaScript
import { assert } from 'oak-domain/lib/utils/assert';
|
|
import { OakUploadException } from '../../types/Exception';
|
|
import { OakNetworkException } from 'oak-domain/lib/types/Exception';
|
|
// TODO 腾讯云上传代码未测试
|
|
export default class TencentYun {
|
|
name = 'tencent';
|
|
autoInform() {
|
|
return false;
|
|
}
|
|
getConfig(application) {
|
|
const { system } = application;
|
|
const { config } = system;
|
|
const tencentConfig = config.Cos?.tencent;
|
|
assert(tencentConfig);
|
|
const { accessKey } = tencentConfig;
|
|
const account = config.Account?.tencent?.find((ele) => ele.secretId === accessKey);
|
|
assert(account);
|
|
return {
|
|
config: tencentConfig,
|
|
account,
|
|
};
|
|
}
|
|
formKey(extraFile) {
|
|
const { id, extension, objectId } = extraFile;
|
|
assert(objectId);
|
|
return `extraFile/${objectId}${extension ? '.' + extension : ''}`;
|
|
}
|
|
async upload(options) {
|
|
const { extraFile, uploadFn, file, uploadToAspect, getPercent } = options;
|
|
const uploadMeta = extraFile.uploadMeta;
|
|
assert(extraFile.enableChunkedUpload !== true, '暂不支持分片上传');
|
|
let response;
|
|
try {
|
|
response = await uploadFn({
|
|
file,
|
|
name: 'file',
|
|
uploadUrl: uploadMeta.uploadHost,
|
|
formData: {
|
|
key: uploadMeta.key,
|
|
policy: uploadMeta.policy,
|
|
signature: uploadMeta.signature,
|
|
'q-sign-algorithm': uploadMeta.algorithm,
|
|
'q-ak': uploadMeta.accessKey,
|
|
'q-key-time': uploadMeta.keyTime,
|
|
'q-signature': uploadMeta.signature,
|
|
},
|
|
autoInform: true,
|
|
getPercent,
|
|
uploadId: extraFile.id
|
|
});
|
|
}
|
|
catch (err) {
|
|
// 网络错误
|
|
throw new OakNetworkException('网络异常,请求失败');
|
|
}
|
|
let isSuccess = false;
|
|
if (process.env.OAK_PLATFORM === 'wechatMp') {
|
|
// 小程序端上传 使用wx.uploadFile
|
|
// 待测试
|
|
if (response.errMsg === 'uploadFile:ok') {
|
|
const data = JSON.parse(response.data);
|
|
isSuccess = data.status === 200 || data.status === 204;
|
|
}
|
|
}
|
|
else {
|
|
isSuccess = response.status === 200 || response.status === 204;
|
|
}
|
|
// 解析回调
|
|
if (isSuccess) {
|
|
return;
|
|
}
|
|
throw new OakUploadException('文件上传腾讯云失败');
|
|
}
|
|
composeFileUrl(options) {
|
|
const { application, extraFile, style } = options;
|
|
const { config: tencentCosConfig } = this.getConfig(application);
|
|
if (tencentCosConfig) {
|
|
let bucket = tencentCosConfig.buckets.find((ele) => ele.name === extraFile.bucket);
|
|
if (bucket) {
|
|
const { domain, protocol } = bucket;
|
|
let protocol2 = protocol;
|
|
if (protocol instanceof Array) {
|
|
// protocol存在https: 说明域名有证书
|
|
const index = protocol.includes('https:')
|
|
? protocol.findIndex((ele) => ele === 'https:')
|
|
: 0;
|
|
protocol2 = protocol[index];
|
|
}
|
|
return `${protocol2}//${domain}/${this.formKey(extraFile)}${style ? style : ''}`;
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
}
|
|
;
|