import { assert } from 'oak-domain/lib/utils/assert'; import { OakUploadException } from '../../types/Exception'; import { OakNetworkException } from 'oak-domain/lib/types/Exception'; import { chunkUpload } from './common'; export default class ALiYun { name = 'aliyun'; autoInform() { return false; } getConfig(application) { const { system } = application; const { config } = system; const aliyunConfig = config.Cos?.aliyun; assert(aliyunConfig); const { accessKey } = aliyunConfig; const account = config.Account?.ali?.find((ele) => ele.accessKeyId === accessKey); assert(account); return { config: aliyunConfig, account, }; } formKey(extraFile) { const { id, extension, objectId } = extraFile; assert(objectId); return `extraFile/${objectId}${extension ? '.' + extension : ''}`; } async upload(options) { const { extraFile, uploadFn, file, uploadToAspect, getPercent, onChunkSuccess } = options; const uploadMeta = extraFile.uploadMeta; if (extraFile.enableChunkedUpload) { return chunkUpload({ extraFile, uploadFn, file, getPercent, parallelism: options.parallelism, retryTimes: options.retryTimes, retryDelay: options.retryDelay, onChunkSuccess: onChunkSuccess, }); } else { let response; try { response = await uploadFn(file, 'file', uploadMeta.uploadHost, { key: uploadMeta.key, policy: uploadMeta.policy, ossAccessKeyId: uploadMeta.accessKey, signature: uploadMeta.signature, }, true, getPercent, 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 === 204); } } else { isSuccess = !!(response.status === 204); } // 解析回调 if (isSuccess) { return; } } throw new OakUploadException('文件上传阿里云失败'); } composeFileUrl(options) { const { application, extraFile, style } = options; const { config: aliyunCosConfig } = this.getConfig(application); if (aliyunCosConfig) { let bucket = aliyunCosConfig.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 ''; } } ;