const COS = require('./lib/cos-wx-sdk-v5.js'); // For development use// const COS = require('./lib/cos-wx-sdk-v5.min.js'); // Use the minified version for production
npm install cos-wx-sdk-v5
var COS = require('cos-wx-sdk-v5'); for referencing. For more details, see npm Support.examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com.examplebucket-1250000000.cos.accelerate.myqcloud.com.const COS = require('./lib/cos-wx-sdk-v5.js'); // For development use// const COS = require('./lib/cos-wx-sdk-v5.min.js'); // Use the minified version for production// console.log(COS.version); The sdk version must be at least 1.7.2const cos = new COS({SecretId: 'your_tmpSecretId', // temporary SecretId issued by the sts serviceSecretKey: 'your_tmpSecretKey', // temporary SecretKey issued by the sts serviceSecurityToken: 'your_sessionToken', // temporary SessionToken issued by the sts serviceStartTime: 1720770679403, // It is recommended to pass the server time to avoid signature errors caused by inaccurate client timeExpiredTime: 1720771991367, // expiration time of the temporary keySimpleUploadMethod: 'putObject', // Strongly recommended. For advanced upload and batch upload, use putObject when internally performing simple uploads for small files. The sdk version must be at least v1.3.0.});
const COS = require('./lib/cos-wx-sdk-v5.js'); // For development use// const COS = require('./lib/cos-wx-sdk-v5.min.js'); // Use the minified version for productionconst cos = new COS({SimpleUploadMethod: 'putObject', // Strongly recommended. For advanced upload and batch upload, use putObject when internally performing simple uploads for small files. The sdk version must be at least v1.3.0.getAuthorization: async function (options, callback) {const data = await fetchSts('xxxx'); // You need to implement the logic to obtain temporary keyscallback({TmpSecretId: data.credentials.tmpSecretId,TmpSecretKey: data.credentials.tmpSecretKey,SecurityToken: data.credentials.sessionToken,// It is recommended to return the server time as the signature start time to avoid signature errors caused by large deviations in the client's local time.StartTime: data.startTime, // timestamp in seconds, e.g. 1580000000ExpiredTime: data.expiredTime, // timestamp in seconds, e.g. 1580000000ScopeLimit: true, // Fine-grained control permissions need to be set to true, which will restrict the key to be reused only for identical requests});}});
const COS = require('./lib/cos-wx-sdk-v5.js'); // For development use// const COS = require('./lib/cos-wx-sdk-v5.min.js'); // Use the minified version for productionconst cos = new COS({SimpleUploadMethod: 'putObject', // Strongly recommended. For advanced upload and batch upload, use putObject when internally performing simple uploads for small files. The sdk version must be at least v1.3.0.getAuthorization: function (options, callback) {// It is not called during initialization; it is only entered when a cos method (e.g., cos.putObject) is called.// Asynchronously obtain temporary keys// Server-side JS sample: https://github.com/tencentyun/cos-js-sdk-v5/blob/master/server/// For server-side implementations in other languages, refer to the COS STS SDK: https://github.com/tencentyun/qcloud-cos-sts-sdk// For detailed STS documentation, refer to: https://www.tencentcloud.com/document/product/436/14048const stsUrl = 'http://example.com/server/sts'; // Replace with your own backend servicewx.request({url: stsUrl,data: {bucket: options.Bucket,region: options.Region,},dataType: 'json',success: function (result) {const data = result.data;const credentials = data && data.credentials;if (!data || !credentials) return console.error('credentials invalid');// Check the credentials formatconsole.log(credentials);callback({TmpSecretId: credentials.tmpSecretId,TmpSecretKey: credentials.tmpSecretKey,// For SDK versions before v1.2.0, use XCosSecurityToken instead of SecurityTokenSecurityToken: credentials.sessionToken,// It is recommended to return the server time as the start time of the signature to avoid signature errors caused by large deviations in the user's local browser time.StartTime: data.startTime, // Timestamp in seconds, e.g., 1580000000ExpiredTime: data.expiredTime, // timestamp in seconds, e.g. 1580000900});}});}});export default cos;
import cos from 'utils/cos';let taskId;// Upload the file, where file is the selected fileasync function upload(file) {try {const data = await cos.uploadFile({Bucket: 'examplebucket-1250000000', // Replace with your own bucket name, requiredRegion: 'COS_REGION', // bucket region, required fieldKey: '1.jpg', // Object key stored in the bucket (e.g., 1.jpg, a/b/test.txt), requiredFilePath: file.path, /* required */FileSize: file.size, /* required for versions before v1.4.3, optional for v1.4.3 and later */SliceSize: 1024 * 1024 * 5, // Threshold for multipart upload; files over 5MB use multipart upload, files under 5MB use simple upload. Configurable, optionalonProgress: function(progressData) {console.log('Upload progress:', progressData);},onTaskReady: function(id) { // optionaltaskId = id;},});console.log('Upload succeeded', data);} catch (e) {console.error('Upload failed', e);}}// Listen to the upload queuecos.on('update-list', data => {console.log(data);});// Pause the upload taskcos.pauseTask(taskId);// Resume the upload taskcos.restartTask(taskId);// Cancel the upload taskcos.cancelTask(taskId);
const COS = require('./lib/cos-wx-sdk-v5.js'); // For development use// const COS = require('./lib/cos-wx-sdk-v5.min.js'); // Use the minified version for production// To view and manage SECRETID and SECRETKEY, please log in to https://console.tencentcloud.com/cam/capiconst cos = new COS({SecretId: process.env.SecretId, // It is recommended to obtain via environment variables; User's SecretId, it is recommended to use sub-account keys, follow the principle of least privilege for authorization to reduce usage risks. For obtaining sub-account keys, refer to https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1SecretKey: process.env.SecretKey, // It is recommended to obtain via environment variables; User's SecretKey, it is recommended to use sub-account keys, follow the principle of least privilege for authorization to reduce usage risks. For obtaining sub-account keys, refer to https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1});
Parameter Name | Parameter Description | Type | Required or Not |
SecretId | User's SecretId. It is recommended to use it only during frontend debugging to avoid exposing the key. | String | No |
SecretKey | User's SecretKey. It is recommended that it be used only for front-end debugging to avoid the key being exposed. | String | No |
SecurityToken | The sessionToken of the obtained temporary credentials (supported since v1.7.2 version). When temporary credentials are passed for SecretId and SecretKey, SecurityToken is required. | String | No |
StartTime | The valid start timestamp of the obtained temporary credentials (supported since v1.7.2 version), unit: seconds. When temporary credentials are passed for SecretId and SecretKey, it is recommended to pass StartTime. | Number | No |
ExpiredTime | The valid expiration timestamp of the obtained temporary credentials (supported since v1.7.2 version), unit: seconds. When temporary credentials are passed for SecretId and SecretKey, it is recommended to pass ExpiredTime. | Number | No |
FileParallelLimit | The concurrency of file uploads under the same instance, default value: 3 | Number | No |
ChunkParallelLimit | Concurrency for chunks of the same uploaded file, default value: 3 | Number | No |
ChunkRetryTimes | Number of retry attempts for errors during multipart uploads and multipart copies, default value: 2 (including the initial request, totaling 3 attempts) | Number | No |
ChunkSize | Size in bytes for each part during multipart uploads, default value: 1048576 (1MB) | Number | No |
SliceSize | When uploadFiles is used for batch upload, if the file size exceeds this value, slice upload (sliceUploadFile) will be used; otherwise, simple upload (putObject) will be employed. Default value: 1048576 (1MB). | Number | No |
CopyChunkParallelLimit | Concurrency for multipart copy operations during block copy processes, default value: 20 | Number | No |
CopyChunkSize | Size in bytes for each part when sliceCopyFile is used for multipart file copy, default value: 10485760 (10MB) | Number | No |
CopySliceSize | When sliceCopyFile is used for multipart file copy, if the file size exceeds this value, multipart copy (sliceCopyFile) will be used; otherwise, simple copy (putObjectCopy) will be employed. Default value: 10485760 (10MB). | Number | No |
ProgressInterval | Callback frequency of the onProgress callback method for upload progress, unit: ms, default value: 1000 | Number | No |
Protocol | The protocol used when a request is sent. Options include https:, http:. In mini programs, only https can be used. | String | No |
ServiceDomain | The request domain name when the getService method is invoked, for example service.cos.myqcloud.com | String | No |
Domain | The custom request domain name when APIs for bucket and object operations are invoked. Templates can be used, for example "{Bucket}.cos.{Region}.myqcloud.com", meaning the Bucket and Region passed in parameters will be replaced during API calls. | String | No |
UploadQueueSize | Maximum upload queue size. Tasks exceeding this limit will be cleaned up if their status is not waiting, checking, or uploading. Default: 10000. | Number | No |
UploadCheckContentMd5 | Force validation of Content-MD5 for file uploads. This calculates the MD5 of the request Body and places it in the Content-MD5 header field. Default: false. | Boolean | No |
getAuthorization | Callback method for obtaining signatures. This parameter is mandatory when SecretId and SecretKey are not provided. Note: This callback method is passed in during instance initialization and will be executed when the instance is used to invoke interfaces to retrieve the signature. | Function | No |
UseAccelerate | Whether to enable the global acceleration domain. Default: false. If set to true, the bucket must have the global acceleration feature enabled. For details, see Enable Global Acceleration | Boolean | No |
SimpleUploadMethod | The method name for internal simple upload of small files in advanced upload and batch upload. Options include 'postObject' or 'putObject', default is 'postObject' (this parameter is supported starting from version v1.3.0). | String | No |
getAuthorization: function(options, callback) { ... }
Parameter Name | Parameter Description | Type |
options | Parameters required for obtaining a temporary key. | Object |
- Bucket | Bucket name. The naming rule is BucketName-APPID. The bucket name entered here must be in this format. | String |
- Region | Bucket region. See values in Regions and Access Domains | String |
callback | Callback method after a temporary key is obtained. | Function |
Property Name | Parameter Description | Type | Required or Not |
TmpSecretId | tmpSecretId of the obtained temporary key. | String | Yes |
TmpSecretKey | tmpSecretKey of the obtained temporary key. | String | Yes |
SecurityToken | The sessionToken of the obtained temporary key, which corresponds to the x-cos-security-token field in the header. SDK versions prior to v1.2.0 use XCosSecurityToken instead of SecurityToken. | String | Yes |
StartTime | The start time of key acquisition, i.e., the timestamp of the acquisition moment in seconds (startTime, for example: 1580000000). This is used as the signature start time to prevent signature expiration issues caused by frontend time deviation. | String | No |
ExpiredTime | expiredTime of the obtained temporary key. The expiration timestamp in seconds, for example: 1580000900 | String | Yes |
https://h.trace.qq.com;https://oth.str.beacon.qq.com;https://otheve.beacon.qq.com.// The complete demo can be found at: https://github.com/tencentyun/cos-wx-sdk-v5/blob/master/demo/tools.jsconst Beacon = require('./lib/beacon_mp.min');new COS({BeaconReporter,})
// Here the initialization process and upload parameters are omitted.const cos = new COS({ ... });cos.uploadFile({ ... }, function(err, data) {if (err) {console.log('Upload error', err);} else {console.log('Upload succeeded', data);}});
// Here the initialization process and upload parameters are omitted.const cos = new COS({ ... });cos.uploadFile({ ... }).then(data => {console.log('Upload succeeded', data);}).catch(err => {console.log('Upload error', err);});
async function upload() {// Here the initialization process and upload parameters are omitted.const cos = new COS({ ... });try {const data = await cos.uploadFile({ ... });return { err: null, data: data }} catch (err) {return { err: err, data: null };}}// The return value of the request can be obtained synchronously. Here is an example. The actual returned data format can be customized.const uploadResult = await upload();if (uploadResult.err) {console.log('Upload error', uploadResult.err);} else {console.log('Upload succeeded', uploadResult.data);}
var COS = require('./lib/cos-wx-sdk-v5');/* Initialize cos */const cos = new COS({getAuthorization: function (options, callback) {wx.request({method: 'GET',url: config.stsUrl,dataType: 'json',success: function (result) {var data = result.data;var credentials = data && data.credentials;if (!data || !credentials) {console.error('Failed to obtain temporary key');return;}callback({TmpSecretId: credentials.tmpSecretId,TmpSecretKey: credentials.tmpSecretKey,SecurityToken: credentials.sessionToken,StartTime: data.startTime,ExpiredTime: data.expiredTime,});},fail: function (err) {console.error('Failed to request temporary key:', err);}});}});function createBucket() {cos.putBucket({Bucket: 'examplebucket-1250000000',Region: 'ap-beijing'}, function (err, data) {if (err) {console.log('Failed to create bucket', err);} else {console.log('Create bucket succeeded', data);console.log('Bucket location:', data.Location);}});}
var COS = require('./lib/cos-wx-sdk-v5');var config = require('./config');/* Initialize cos */const cos = new COS({getAuthorization: function (options, callback) {wx.request({method: 'GET',url: config.stsUrl,dataType: 'json',success: function (result) {var data = result.data;var credentials = data && data.credentials;if (!data || !credentials) {console.error('Failed to obtain temporary key');return;}callback({TmpSecretId: credentials.tmpSecretId,TmpSecretKey: credentials.tmpSecretKey,SecurityToken: credentials.sessionToken,StartTime: data.startTime,ExpiredTime: data.expiredTime,});},fail: function (err) {console.error('Failed to request temporary key:', err);}});}});/* Obtain bucket list */function getBucketList() {cos.getService(function (err, data) {if (err) {console.log('Failed to obtain bucket list', err);} else {console.log('Obtain bucket list succeeded', data);console.log(data && data.Buckets);}});}
simple upload of objects and multipart upload. See Authorization Guide./* Initialize cos */const cos = new COS({// getAuthorization: funciton() {}, // Refer to the initialization aboveSimpleUploadMethod: 'putObject', // Strongly recommended, for advanced upload and batch upload, internally perform simple upload for small files using putObject});function handleFileInUploading(fileName, filePath) {cos.uploadFile({Bucket: 'examplebucket-1250000000', /* Replace with your own bucket, required field */Region: 'COS_REGION', /* bucket region, required field */Key: fileName, /* Object key stored in the bucket (e.g., 1.jpg, a/b/test.txt, image.jpg) supports Chinese characters, required field */FilePath: filePath, /* upload file path, required field */SliceSize: 1024 * 1024 * 5, /* Threshold for multipart upload; files over 5MB use multipart upload, files under 5MB use simple upload. Configurable, optional */onProgress: function(progressData) {console.log(JSON.stringify(progressData));}}, function(err, data) {if (err) {console.log('Upload failed', err);} else {console.log('Upload succeeded');}});}/* Select a file to get the temporary path (taking image selection as an example; for selecting other files, see the official Mini Program api) */wx.chooseImage({count: 1, // default 9sizeType: ['original'], // specifies whether to use the original or compressed image, uses the original by defaultsourceType: ['album', 'camera'], // specifies whether the source is album or camera, includes both by defaultsuccess: function (res) {const filePath = res.tempFiles[0].path;const fileName = filePath.substr(filePath.lastIndexOf('/') + 1);handleFileInUploading(fileName, filePath);}});
var COS = require('./lib/cos-wx-sdk-v5');var config = require('./config');/* Initialize cos */const cos = new COS({getAuthorization: function (options, callback) {wx.request({method: 'GET',url: config.stsUrl,dataType: 'json',success: function (result) {var data = result.data;var credentials = data && data.credentials;if (!data || !credentials) {console.error('Failed to obtain temporary key');return;}callback({TmpSecretId: credentials.tmpSecretId,TmpSecretKey: credentials.tmpSecretKey,SecurityToken: credentials.sessionToken,StartTime: data.startTime,ExpiredTime: data.expiredTime,});},fail: function (err) {console.error('Failed to request temporary key:', err);}});}});/* Obtain the object list in the bucket */function getObjectList() {cos.getBucket({Bucket: 'examplebucket-1250000000',Region: 'ap-beijing',Prefix: 'exampledir/', // specify the file prefix to list here}, function (err, data) {if (err) {console.log('Failed to obtain the object list', err);} else {console.log('Successfully obtained the object list', data);console.log(err || data.Contents);}});}
var COS = require('./lib/cos-wx-sdk-v5');var config = require('./config');/* Initialize cos */const cos = new COS({getAuthorization: function (options, callback) {wx.request({method: 'GET',url: config.stsUrl,dataType: 'json',success: function (result) {var data = result.data;var credentials = data && data.credentials;if (!data || !credentials) {console.error('Failed to obtain temporary key');return;}callback({TmpSecretId: credentials.tmpSecretId,TmpSecretKey: credentials.tmpSecretKey,SecurityToken: credentials.sessionToken,StartTime: data.startTime,ExpiredTime: data.expiredTime,});},fail: function (err) {console.error('Failed to request temporary key:', err);}});}});/* Download object */function getObject() {cos.getObject({Bucket: 'examplebucket-1250000000',Region: 'ap-beijing',Key: 'exampleobject.txt',}, function (err, data) {if (err) {console.log('Failed to download the object', err);} else {console.log('Successfully downloaded the object', data);console.log(err || data.Body);}});}
var COS = require('./lib/cos-wx-sdk-v5');var config = require('./config');/* Initialize cos */const cos = new COS({getAuthorization: function (options, callback) {wx.request({method: 'GET',url: config.stsUrl,dataType: 'json',success: function (result) {var data = result.data;var credentials = data && data.credentials;if (!data || !credentials) {console.error('Failed to obtain temporary key');return;}callback({TmpSecretId: credentials.tmpSecretId,TmpSecretKey: credentials.tmpSecretKey,SecurityToken: credentials.sessionToken,StartTime: data.startTime,ExpiredTime: data.expiredTime,});},fail: function (err) {console.error('Failed to request temporary key:', err);}});}});/* Delete object */function deleteObject() {cos.deleteObject({Bucket: 'examplebucket-1250000000',Region: 'ap-beijing',Key: 'picture.jpg',}, function (err, data) {if (err) {console.log('Failed to delete object', err);} else {console.log('Successfully deleted object', data);console.log(err || data);}});}
Feedback