Skip to content

Commit

Permalink
Dev/callback (#210)
Browse files Browse the repository at this point in the history
上传支持 callback
  • Loading branch information
livehigh authored Jun 28, 2024
1 parent 1c0e9c4 commit c3bf0c3
Show file tree
Hide file tree
Showing 10 changed files with 364 additions and 67 deletions.
85 changes: 60 additions & 25 deletions demo/demo.js
Original file line number Diff line number Diff line change
Expand Up @@ -916,6 +916,29 @@ function deleteBucketEncryption() {
);
}

var callback = {
callbackUrl: 'http://xxx/callback',
callbackHost: 'xxx',
callbackBody: 'key=${object}&etag=${etag}&my_var=${x:my_var}&my_var1=123',
callbackBodyType: 'application/x-www-form-urlencoded',
};
var callbackVar = { 'x:my_var': 'value1' };

var returnBody = {
bucket: '${bucket}',
key: '${object}',
filesize: '${size}',
mime_type: '${mimeType}',
// 视频类型
// video_bit_rate: '${videoInfo.video.bit_rate}',
// "video_codec_name": "${videoInfo.video.codec_name}",
// "video_profile": "${videoInfo.video.profile}",
// "video_pix_fmt": "${videoInfo.video.pix_fmt}",
// "audio_bit_rate": "${videoInfo.audio.bit_rate}",
// "audio_codec_name": "${videoInfo.audio.codec_name}",
// "duration": "${videoInfo.format.duration}",
};

function putObject() {
// 创建测试文件
var filename = '1mb.zip';
Expand All @@ -928,23 +951,29 @@ function putObject() {
Key: filename, // 必须
// 常见场景是使用 input[type="file"] 标签选择文件后上传,可参考 selectFileToUpload
Body: blob,
// Callback: COS.util.encodeBase64(JSON.stringify(callback)),
// ReturnBody: COS.util.encodeBase64(JSON.stringify(returnBody)),
// PicOperations: '{"is_pic_info": 1, "rules": [{"fileid": "test.jpg", "rule": "imageMogr2/thumbnail/!50p"}]}',
onTaskReady: function (tid) {
TaskId = tid;
logger.log('onTaskReady', tid);
},
onTaskStart: function (info) {
logger.log('onTaskStart', info);
},
onProgress: function (progressData) {
logger.log(JSON.stringify(progressData));
},
Headers: {
// 万象持久化接口,上传时持久化
// 'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "test.jpg", "rule": "imageMogr2/thumbnail/!50p"}]}'
},
},
function (err, data) {
logger.log('putObject:', err.code || data);
if (err) {
console.log('上传失败');
} else {
console.log('上传成功');
if (data.CallbackError) {
console.log('回调失败', data.CallbackError?.Code);
} else {
console.log('回调成功', data.CallbackBody);
}
}
logger.log('putObject:', err || data);
}
);
}
Expand Down Expand Up @@ -1271,13 +1300,26 @@ function uploadFile() {
Key: filename,
Body: blob,
SliceSize: 1024 * 1024 * 5, // 大于5mb才进行分块上传
Callback: COS.util.encodeBase64(JSON.stringify(callback)),
// ReturnBody: COS.util.encodeBase64(JSON.stringify(returnBody)),
// PicOperations: '{"is_pic_info": 1, "rules": [{"fileid": "test.jpg", "rule": "imageMogr2/thumbnail/!50p"}]}',
onProgress: function (info) {
var percent = Math.floor(info.percent * 10000) / 100;
var speed = Math.floor((info.speed / 1024 / 1024) * 100) / 100;
logger.log('进度:' + percent + '%; 速度:' + speed + 'Mb/s;');
},
},
function (err, data) {
if (err) {
console.log('上传失败');
} else {
console.log('上传成功');
if (data.CallbackError) {
console.log('回调失败', data.CallbackError?.Code);
} else {
console.log('回调成功', data.CallbackBody);
}
}
logger.log('uploadFile:', err || data);
}
);
Expand All @@ -1291,10 +1333,7 @@ function sliceUploadFile() {
Region: config.Region,
Key: '3mb.jpg', // 必须
Body: blob,
Headers: {
// 支持万象持久化接口,上传时持久化
// 'Pic-Operations': '{"is_pic_info": 1, "rules": [{"fileid": "test.jpg", "rule": "imageMogr2/thumbnail/!50p"}]}'
},
// Callback: COS.util.encodeBase64(JSON.stringify(callback)),
onTaskReady: function (tid) {
TaskId = tid;
},
Expand All @@ -1316,19 +1355,17 @@ function selectFileToUpload() {
util.selectLocalFile(function (files) {
var file = files && files[0];
if (!file) return;
if (file.size > 1024 * 1024) {
if (file.size > 1024 * 1024 * 3) {
cos.sliceUploadFile(
{
Bucket: config.Bucket, // Bucket 格式:test-1250000000
Region: config.Region,
Key: file.name,
Body: file,
onTaskReady: function (tid) {
TaskId = tid;
},
onProgress: function (progressData) {
logger.log('onProgress', JSON.stringify(progressData));
},
// Callback: COS.util.encodeBase64(JSON.stringify(callback)),
// CallbackVar: COS.util.encodeBase64(JSON.stringify(callbackVar)),
// ReturnBody: COS.util.encodeBase64(JSON.stringify(returnBody)),
// PicOperations: '{"is_pic_info": 1, "rules": [{"fileid": "test.jpg", "rule": "imageMogr2/thumbnail/!50p"}]}',
},
function (err, data) {
logger.log('selectFileToUpload:', err || data);
Expand All @@ -1341,12 +1378,10 @@ function selectFileToUpload() {
Region: config.Region,
Key: file.name,
Body: file,
onTaskReady: function (tid) {
TaskId = tid;
},
onProgress: function (progressData) {
logger.log(JSON.stringify(progressData));
},
// Callback: COS.util.encodeBase64(JSON.stringify(callback)),
// CallbackVar: COS.util.encodeBase64(JSON.stringify(callbackVar)),
// ReturnBody: COS.util.encodeBase64(JSON.stringify(returnBody)),
// PicOperations: '{"is_pic_info": 1, "rules": [{"fileid": "test.jpg", "rule": "imageMogr2/thumbnail/!50p"}]}',
},
function (err, data) {
logger.log('selectFileToUpload:', err || data);
Expand Down
90 changes: 76 additions & 14 deletions dist/cos-js-sdk-v5.js
Original file line number Diff line number Diff line change
Expand Up @@ -7281,7 +7281,7 @@ module.exports = function(module) {
/*! exports provided: name, version, description, main, types, scripts, repository, keywords, author, license, bugs, homepage, dependencies, devDependencies, default */
/***/ (function(module) {

module.exports = JSON.parse("{\"name\":\"cos-js-sdk-v5\",\"version\":\"1.8.1\",\"description\":\"JavaScript SDK for [腾讯云对象存储](https://cloud.tencent.com/product/cos)\",\"main\":\"dist/cos-js-sdk-v5.js\",\"types\":\"index.d.ts\",\"scripts\":{\"prettier\":\"prettier --write src demo/demo.js demo/CIDemos/*.js test/test.js server/sts.js lib/request.js index.d.ts\",\"server\":\"node server/sts.js\",\"dev\":\"cross-env NODE_ENV=development webpack -w --mode=development\",\"build\":\"cross-env NODE_ENV=production webpack --mode=production\",\"cos-auth.min.js\":\"uglifyjs ./demo/common/cos-auth.js -o ./demo/common/cos-auth.min.js -c -m\",\"test\":\"jest --runInBand --coverage\"},\"repository\":{\"type\":\"git\",\"url\":\"git+https://github.com/tencentyun/cos-js-sdk-v5.git\"},\"keywords\":[],\"author\":\"carsonxu\",\"license\":\"ISC\",\"bugs\":{\"url\":\"https://github.com/tencentyun/cos-js-sdk-v5/issues\"},\"homepage\":\"https://github.com/tencentyun/cos-js-sdk-v5#readme\",\"dependencies\":{\"@xmldom/xmldom\":\"^0.8.6\"},\"devDependencies\":{\"@babel/core\":\"7.17.9\",\"@babel/plugin-transform-runtime\":\"7.18.10\",\"@babel/preset-env\":\"7.16.11\",\"babel-loader\":\"8.2.5\",\"body-parser\":\"^1.18.3\",\"cross-env\":\"^5.2.0\",\"express\":\"^4.16.4\",\"jest\":\"^29.3.1\",\"jest-environment-jsdom\":\"^29.3.1\",\"prettier\":\"^3.0.1\",\"qcloud-cos-sts\":\"^3.0.2\",\"request\":\"^2.87.0\",\"terser-webpack-plugin\":\"4.2.3\",\"uglifyjs\":\"^2.4.11\",\"webpack\":\"4.46.0\",\"webpack-cli\":\"4.10.0\"}}");
module.exports = JSON.parse("{\"name\":\"cos-js-sdk-v5\",\"version\":\"1.8.2\",\"description\":\"JavaScript SDK for [腾讯云对象存储](https://cloud.tencent.com/product/cos)\",\"main\":\"dist/cos-js-sdk-v5.js\",\"types\":\"index.d.ts\",\"scripts\":{\"prettier\":\"prettier --write src demo/demo.js demo/CIDemos/*.js test/test.js server/sts.js lib/request.js index.d.ts\",\"server\":\"node server/sts.js\",\"dev\":\"cross-env NODE_ENV=development webpack -w --mode=development\",\"build\":\"cross-env NODE_ENV=production webpack --mode=production\",\"cos-auth.min.js\":\"uglifyjs ./demo/common/cos-auth.js -o ./demo/common/cos-auth.min.js -c -m\",\"test\":\"jest --runInBand --coverage\"},\"repository\":{\"type\":\"git\",\"url\":\"git+https://github.com/tencentyun/cos-js-sdk-v5.git\"},\"keywords\":[],\"author\":\"carsonxu\",\"license\":\"ISC\",\"bugs\":{\"url\":\"https://github.com/tencentyun/cos-js-sdk-v5/issues\"},\"homepage\":\"https://github.com/tencentyun/cos-js-sdk-v5#readme\",\"dependencies\":{\"@xmldom/xmldom\":\"^0.8.6\"},\"devDependencies\":{\"@babel/core\":\"7.17.9\",\"@babel/plugin-transform-runtime\":\"7.18.10\",\"@babel/preset-env\":\"7.16.11\",\"babel-loader\":\"8.2.5\",\"body-parser\":\"^1.18.3\",\"cross-env\":\"^5.2.0\",\"express\":\"^4.16.4\",\"jest\":\"^29.3.1\",\"jest-environment-jsdom\":\"^29.3.1\",\"prettier\":\"^3.0.1\",\"qcloud-cos-sts\":\"^3.0.2\",\"request\":\"^2.87.0\",\"terser-webpack-plugin\":\"4.2.3\",\"uglifyjs\":\"^2.4.11\",\"webpack\":\"4.46.0\",\"webpack-cli\":\"4.10.0\"}}");

/***/ }),

Expand Down Expand Up @@ -7340,7 +7340,7 @@ function sliceUploadFile(params, callback) {
var metaHeaders = {};
util.each(params.Headers, function (val, k) {
var shortKey = k.toLowerCase();
if (shortKey.indexOf('x-cos-meta-') === 0 || shortKey === 'pic-operations') {
if (shortKey.indexOf('x-cos-meta-') === 0 || ['pic-operations', 'x-cos-callback', 'x-cos-callback-var', 'x-cos-return-body'].includes(shortKey)) {
metaHeaders[k] = val;
}
});
Expand Down Expand Up @@ -11556,20 +11556,51 @@ function multipartComplete(params, callback) {
isLocation: true
});
var res = data.CompleteMultipartUploadResult || {};
// pic-operations 处理
if (res.ProcessResults) {
if (res && res.ProcessResults) {
res.UploadResult = {
OriginalInfo: {
Key: res.Key,
Location: url,
ETag: res.ETag,
ImageInfo: res.ImageInfo
},
ProcessResults: res.ProcessResults
res.UploadResult = {
OriginalInfo: {
Key: res.Key,
Location: url,
ETag: res.ETag,
ImageInfo: res.ImageInfo
},
ProcessResults: res.ProcessResults
};
delete res.ImageInfo;
delete res.ProcessResults;
}
// callback 处理
if (res.CallbackResult) {
var callbackResult = res.CallbackResult;
if (callbackResult.Status === '200' && callbackResult.CallbackBody) {
try {
res.CallbackBody = JSON.parse(util.decodeBase64(callbackResult.CallbackBody));
} catch (e) {
res.CallbackBody = {};
}
} else {
res.CallbackError = callbackResult.Error || {};
}
delete res.CallbackResult;
}
// returnBody 处理
if (res.ReturnBodyResult) {
var returnBodyResult = res.ReturnBodyResult;
if (returnBodyResult.Status === '200' && returnBodyResult.ReturnBody) {
try {
res.ReturnBody = JSON.parse(util.decodeBase64(returnBodyResult.ReturnBody));
} catch (e) {
res.ReturnBody = {};
}
} else {
res.ReturnError = {
Code: returnBodyResult.Code,
Message: returnBodyResult.Message,
Status: returnBodyResult.Status
};
delete res.ImageInfo;
delete res.ProcessResults;
}
delete res.ReturnBodyResult;
}
var result = util.extend(res, {
Location: url,
Expand Down Expand Up @@ -12564,6 +12595,29 @@ function _submitRequest(params, callback) {
err = util.extend(err || {}, attrs);
callback(err, null);
} else {
// putObject 返回回调处理
if (params.Action === 'name/cos:PutObject') {
var pHeaders = {};
for (var i in params.headers) {
var key = i.toLowerCase();
pHeaders[key] = params.headers[i];
}
if (pHeaders['x-cos-callback']) {
if (data.Error) {
data.CallbackError = util.clone(data.Error);
delete data.Error;
} else {
data.CallbackBody = util.clone(data);
}
} else if (pHeaders['x-cos-return-body']) {
if (data.Error) {
data.ReturnError = util.clone(data.Error);
delete data.Error;
} else {
data.ReturnBody = util.clone(data);
}
}
}
data = util.extend(data || {}, attrs);
callback(null, data);
}
Expand Down Expand Up @@ -14190,7 +14244,10 @@ var formatParams = function formatParams(apiName, params) {
'x-cos-server-side-encryption-cos-kms-key-id': 'SSEKMSKeyId',
'x-cos-server-side-encryption-context': 'SSEContext',
// 上传时图片处理
'Pic-Operations': 'PicOperations'
'Pic-Operations': 'PicOperations',
'x-cos-callback': 'Callback',
'x-cos-callback-var': 'CallbackVar',
'x-cos-return-body': 'ReturnBody'
};
util.each(headerMap, function (paramKey, headerKey) {
if (params[paramKey] !== undefined) {
Expand Down Expand Up @@ -14460,6 +14517,10 @@ var encodeBase64 = function encodeBase64(str, safe) {
}
return base64Str;
};
var decodeBase64 = function decodeBase64(base64Str) {
if (!base64Str) return '';
return base64.decode(base64Str);
};
var simplifyPath = function simplifyPath(path) {
var names = path.split('/');
var stack = [];
Expand Down Expand Up @@ -14553,6 +14614,7 @@ var util = {
isCIHost: isCIHost,
isIOS_QQ: isIOS && isQQ,
encodeBase64: encodeBase64,
decodeBase64: decodeBase64,
simplifyPath: simplifyPath,
readAsBinaryString: readAsBinaryString,
parseResBody: parseResBody
Expand Down
2 changes: 1 addition & 1 deletion dist/cos-js-sdk-v5.min.js

Large diffs are not rendered by default.

12 changes: 12 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1317,6 +1317,10 @@ declare namespace COS {
Location: string;
/** 对象的版本 ID */
VersionId?: VersionId;
CallbackBody?: Record<string, any>;
CallbackError?: Record<string, any>;
ReturnBody?: Record<string, any>;
ReturnError?: Record<string, any>;
}

/** appendObject 接口参数 */
Expand Down Expand Up @@ -1802,6 +1806,10 @@ Bulk:批量模式,恢复时间为24 - 48小时。 */
Location: string;
/** 对象的版本 ID */
VersionId?: VersionId;
CallbackBody?: Record<string, any>;
CallbackError?: Record<string, any>;
ReturnBody?: Record<string, any>;
ReturnError?: Record<string, any>;
}

// abortUploadTask
Expand Down Expand Up @@ -1883,6 +1891,10 @@ Bulk:批量模式,恢复时间为24 - 48小时。 */
Location: string;
/** 对象的版本 ID */
VersionId?: VersionId;
CallbackBody?: Record<string, any>;
CallbackError?: Record<string, any>;
ReturnBody?: Record<string, any>;
ReturnError?: Record<string, any>;
}

// sliceCopyFile
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "cos-js-sdk-v5",
"version": "1.8.1",
"version": "1.8.2",
"description": "JavaScript SDK for [腾讯云对象存储](https://cloud.tencent.com/product/cos)",
"main": "dist/cos-js-sdk-v5.js",
"types": "index.d.ts",
Expand Down
5 changes: 4 additions & 1 deletion src/advance.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,10 @@ function sliceUploadFile(params, callback) {
var metaHeaders = {};
util.each(params.Headers, function (val, k) {
var shortKey = k.toLowerCase();
if (shortKey.indexOf('x-cos-meta-') === 0 || shortKey === 'pic-operations') {
if (
shortKey.indexOf('x-cos-meta-') === 0 ||
['pic-operations', 'x-cos-callback', 'x-cos-callback-var', 'x-cos-return-body'].includes(shortKey)
) {
metaHeaders[k] = val;
}
});
Expand Down
Loading

0 comments on commit c3bf0c3

Please sign in to comment.