oak-general-business/es/utils/cos/qiniu.js

89 lines
3.3 KiB
JavaScript
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 { assert } from 'oak-domain/lib/utils/assert';
import { OakUploadException } from '../../types/Exception';
import { OakNetworkException } from 'oak-domain/lib/types/Exception';
export default class Qiniu {
name = 'qiniu';
autoInform() {
return false;
}
getConfig(application) {
const { system } = application;
const { config } = system;
const qiniuConfig = config.Cos?.qiniu;
assert(qiniuConfig);
const { accessKey } = qiniuConfig;
const account = config.Account?.qiniu?.find(ele => ele.accessKey === accessKey);
assert(account);
return {
config: qiniuConfig,
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, 'file', uploadMeta.uploadHost, {
key: uploadMeta.key,
token: uploadMeta.uploadToken,
}, 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.success === true || data.key);
}
}
else {
const data = await response.json();
isSuccess = !!(data.success === true || data.key);
}
// 解析回调
if (isSuccess) {
return;
}
else {
throw new OakUploadException('文件上传七牛失败');
}
}
// style 多媒体样式
// 访问处理后的文件
// 对于图片文件 1.png ,访问样式链接 https://{domain}/1.png-small.jpg即可获得处理后的 jpg 格式图片
// "-"是默认的样式分隔符,
// 查看文档 https://developer.qiniu.com/kodo/8558/set-the-picture-style
composeFileUrl(options) {
const { application, extraFile, style } = options;
const { config: qiniuCosConfig } = this.getConfig(application);
if (qiniuCosConfig) {
let bucket = qiniuCosConfig.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 '';
}
}
;