t-comm
Version:
专业、稳定、纯粹的工具库
86 lines (83 loc) • 3.03 kB
JavaScript
import { getCOSInstance } from './helper.mjs';
import '../../bite/format-bite.mjs';
import '../../third-party/cos-nodejs-sdk-v5.mjs';
/**
* 获取腾讯云 COS 存储桶中对象的访问 URL
*
* @param secretId - 腾讯云 API 密钥 ID
* @param secretKey - 腾讯云 API 密钥 Key
* @param bucket - COS 存储桶名称
* @param region - COS 存储桶所在区域,例如 ap-beijing
* @param key - 存储在桶里的对象键(例如 1.jpg、a/b/test.txt),支持中文
* @param sign - 是否获取带签名的对象 URL,默认 true(可选)
* @param expires - 签名 URL 的有效时长,单位秒,默认 900 秒(可选)
* @param method - 请求方法,默认 GET(可选)
* @param protocol - 请求协议,可选值:http:、https:(可选)
* @param domain - 自定义域名(可选)
* @param query - 请求中的 query 参数(可选)
* @param headers - 请求中的 header 参数(可选)
* @param forceDownload - 是否强制下载,传入下载后的文件名后将拼接 response-content-disposition 参数(可选)
* @returns Promise 对象,成功时返回对象访问 URL 字符串,失败时返回错误信息
* @throws 当参数不全时会抛出错误
* @example
* ```typescript
* getCosObjectUrl({
* secretId: 'your-secret-id',
* secretKey: 'your-secret-key',
* bucket: 'examplebucket-1250000000',
* region: 'ap-beijing',
* key: '头像.jpg',
* sign: true,
* })
* .then(url => console.log(url))
* .catch(err => console.error(err));
* ```
*/
function getCosObjectUrl(_ref) {
var secretId = _ref.secretId,
secretKey = _ref.secretKey,
bucket = _ref.bucket,
region = _ref.region,
key = _ref.key,
sign = _ref.sign,
expires = _ref.expires,
method = _ref.method,
protocol = _ref.protocol,
domain = _ref.domain,
query = _ref.query,
headers = _ref.headers,
forceDownload = _ref.forceDownload;
return new Promise(function (resolve, reject) {
if (!secretId || !secretKey || !bucket || !region || !key) {
reject('[Get COS Object Url Error] 参数不全');
return;
}
var cos = getCOSInstance(secretId, secretKey);
// https://cloud.tencent.com/document/product/436/35651
cos.getObjectUrl({
Bucket: bucket,
Region: region,
Key: key,
Sign: sign !== false,
Expires: expires,
Method: method,
Protocol: protocol,
Domain: domain,
Query: query,
Headers: headers
}, function (err, data) {
if (data === null || data === void 0 ? void 0 : data.Url) {
var url = data.Url;
// 补充强制下载的参数并重命名下载后的文件
if (forceDownload) {
var separator = url.indexOf('?') > -1 ? '&' : '?';
url += "".concat(separator, "response-content-disposition=attachment;filename=").concat(encodeURIComponent(forceDownload));
}
resolve(url);
return;
}
reject(err || data);
});
});
}
export { getCosObjectUrl };