tencent cloud

Quick Start
Last updated:2026-02-02 11:17:25
Quick Start
Last updated: 2026-02-02 11:17:25

Relevant Resources

To download the SDK source code, see HarmonyOS SDK.
For the sample Demo, see HarmonyOS SDK Demo.
For the SDK change log, see CHANGELOG.
For SDK FAQs, see HarmonyOS SDK FAQ.
For the HarmonyOS official repository address, see @tencentcloud/cos.

Environment Configuration and Preparation

You need a HarmonyOS NEXT application, which can be either an existing project or a newly created empty project. For details, see HarmonyOS NEXT Application Development Guide.
Please ensure your HarmonyOS NEXT application targets API level 12 or higher version.

Installing the SDK

1. Run this command to install the SDK dependencies:
ohpm install @tencentcloud/cos
This will add the following dependency code to your project's oh-package.json5:
"dependencies": {
...
"@tencentcloud/cos":"1.2.1"
}
2. The SDK requires network permission to communicate with the COS server. Add the following permission declaration in the module.json5 under the application module:
...
"requestPermissions":[ { "name" : "ohos.permission.INTERNET",
... } ]
...

Initialize COS Service

Note:
It is recommended that users use temporary keys to call the SDK, further enhancing security through temporary authorization. When applying for temporary keys, follow the principle of least privilege to prevent leakage of resources other than the target bucket or object.
If you must use permanent keys, it is recommended to follow the principle of least privilege to restrict the permission scope of the permanent keys.
For your business security, see Upload Security Limitations for file uploads.

Set API Access Key

Single-Use Temporary Key
Temporary Key Callback
Server-Side Signature Callback
Single Request Signature
Fixed Key (For Testing Only)
Set a single key to a specific CosXmlRequest (such as PutObjectRequest for uploads), which will only be used for the current COS operation (such as uploads).
import { QCloudCredential } from '@tencentcloud/cos';

// Obtain temporary keys (controlled by the business layer)
let credential : QCloudCredential= new QCloudCredential();
credential.secretID = "secretID";
credential.secretKey = "secretKey";
credential.token = "token";
// Both startDate and expirationDate are of type Date, constructed here using a millisecond timestamp
credential.startDate = new Date();
credential.expirationDate = new Date();
You can provide the COS SDK with a callback method to obtain temporary keys. The SDK will use this callback to reobtain temporary keys when the cached temporary key is about to expire for the first time or when it is about to expire.
import { CredentialCallBack, QCloudCredential } from '@tencentcloud/cos';

export class Credential {
/**
* Obtain STS temporary keys
*/
public static sessionCredential: CredentialCallBack = (request)=>{
return new Promise((resolve, reject) => {
// First, obtain a response containing key information from your temporary key server
let httpRequest = http.createHttp();
httpRequest.request(
// Please replace it with the specific sts temporary key acquisition service url
"http://127.0.0.1/sts",
{ method: http.RequestMethod.GET },
(err: BusinessError, data: http.HttpResponse) => {
if (!err) {
const stsSessionQCloudCredentials: StsSessionQCloudCredentials = JSON.parse(data.result.toString());
let credential : QCloudCredential= new QCloudCredential();
credential.secretID = stsSessionQCloudCredentials.credentials.tmpSecretId;
credential.secretKey = stsSessionQCloudCredentials.credentials.tmpSecretKey;
credential.token = stsSessionQCloudCredentials.credentials.sessionToken;
// It is recommended to use the server time as the signature start time to avoid request expiration caused by significant deviations in the user's local device time.
// Both startDate and expirationDate are of type Date, constructed here using a millisecond timestamp,
// The timestamp in the sts response is usually in seconds, so it needs to be multiplied by 1000. If your temporary key service returns timestamps in milliseconds, no multiplication by 1000 is required
credential.startDate = new Date(stsSessionQCloudCredentials.startTime * 1000);
credential.expirationDate = new Date(stsSessionQCloudCredentials.expiredTime * 1000);
httpRequest.destroy();
// Finally, return the temporary key information object
resolve(credential);
} else {
httpRequest.destroy();
reject(err);
}
});
})
}
}

/**
* Temporary Key Entity Definition
*/
export class StsSessionQCloudCredentials{
credentials: StsCredentials;
startTime: number;
expiredTime: number;

constructor(credentials: StsCredentials, startTime: number, expiredTime: number) {
this.credentials = credentials;
this.startTime = startTime;
this.expiredTime = expiredTime;
}
}
export class StsCredentials{
tmpSecretId: string;
tmpSecretKey: string;
sessionToken: string;

constructor(tmpSecretId: string, tmpSecretKey: string, sessionToken: string) {
this.tmpSecretId = tmpSecretId;
this.tmpSecretKey = tmpSecretKey;
this.sessionToken = sessionToken;
}
}
By using a callback method provided to the COS SDK to obtain signatures, the SDK will call this method when initiating network requests. Signature-related logic can be implemented within this method.
// Define the server-side signature callback
let selfSignCallBack = async (request)=>{
// First, obtain a response containing signature information from your server
let httpRequest = http.createHttp();
httpRequest.request(
// Please replace it with the specific signature acquisition service url
"http://127.0.0.1/sign",
{ method: http.RequestMethod.GET },
(err: BusinessError, data: http.HttpResponse) => {
if (!err) {
// Obtain the signature information
let signData: object = JSON.parse(data.result.toString());
// Set the signature header for the request
request.addHeader(HttpHeader.AUTHORIZATION, signData['authorization'])
if(signData['securityToken']){
request.addHeader("x-cos-security-token", signData['securityToken'])
}
httpRequest.destroy();
} else {
httpRequest.destroy();
}
});
}
Set a single request signature to a specific CosXmlRequest (such as PutObjectRequest for uploads), which will only be used for the current COS operation (such as uploads).
// Obtain signature data (controlled by the business layer) let authorization: string = "authorization"; let token: string = "token"; let tokenName: string = "x-cos-security-token";
You can use Tencent Cloud's permanent keys for local debugging during the development phase. Due to the risk of key leakage with this method, it must be replaced with temporary keys prior to release.
import { CredentialCallBack, QCloudCredential } from '@tencentcloud/cos';
export class Credential { /** * Obtain fixed keys. Only used during testing. */ public static constCredential: CredentialCallBack = (request)=>{ return new Promise((resolve, reject) => { let credential : QCloudCredential= new QCloudCredential();
// User's SecretId. It is recommended to use a sub-account key, with authorization following the least privilege guidelines to reduce usage risks. Sub-account key obtainment can be referred to https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1 credential.secretID = "SECRETID";
// User's SecretKey. It is recommended to use a sub-account key, with authorization following the least privilege guidelines to reduce usage risks. Sub-account key obtainment can be referred to https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1 credential.secretKey = "SECRETKEY"; resolve(credential); }) } }

Initialize COS Service

After the COS service is initialized by calling CosXmlBaseService.initDefaultService, you can then call CosXmlBaseService.default() to obtain the default COS service for performing COS operations.
The COS service also supports manual instantiation of CosXmlBaseService to perform COS operations (it is not recommended to instantiate a CosXmlBaseService for every COS operation).
Single-Use Temporary Key
Temporary Key Callback
Server-Side Signature Callback
Single Request Signature
Fixed Key (For Testing Only)
1. Initialize the default Service. You can omit the temporary key callback.
import { CosXmlBaseService, CosXmlServiceConfig } from '@tencentcloud/cos';
// Service configuration
let cosXmlServiceConfig = new CosXmlServiceConfig("ap-guangzhou");
// Initialize the default Service
CosXmlBaseService.initDefaultService(
this.context.getApplicationContext(),
cosXmlServiceConfig
// You can omit the temporary key callback
)
2. Set the credential for CosXmlRequest and use it.
The temporary key for a single operation takes precedence over the temporary key callback configured during CosXmlBaseService initialization. Therefore, the temporary key callback configured in CosXmlBaseService will not affect the setting of a single-operation temporary key. Simply set the credential directly to the CosXmlRequest.
import { CosXmlBaseService, PutObjectRequest, UploadTask } from '@tencentcloud/cos';
// Any CosXmlRequest supports this method, for example, upload PutObjectRequest, download GetObjectRequest, delete DeleteObjectRequest, etc.
// The following uses upload as an example
let putRequest = new PutObjectRequest("examplebucket-1250000000", "exampleobject.txt", "Local file path");
// credential is the single-operation temporary key obtained in the first step "Initialize Key"
putRequest.credential = credential;
let task: UploadTask = CosXmlBaseService.default().upload(putRequest);
task.start();
Initialize the default Service.
import { CosXmlBaseService, CosXmlServiceConfig } from '@tencentcloud/cos';
// Service configuration
let cosXmlServiceConfig = new CosXmlServiceConfig("ap-guangzhou");
// Initialize the default Service
CosXmlBaseService.initDefaultService(
this.context.getApplicationContext(),
cosXmlServiceConfig,
// The temporary key callback obtained in the first step "Initialize Key"
Credential.sessionCredential
)
Initialize the default Service.
import { CosXmlBaseService, CosXmlServiceConfig } from '@tencentcloud/cos';

// Service configuration
let cosXmlServiceConfig = new CosXmlServiceConfig("ap-guangzhou");
// Initialize the default Service
CosXmlBaseService.initDefaultService(
this.context.getApplicationContext(),
cosXmlServiceConfig
)
// The server-side signature callback obtained in the first step "Initialize Key"
CosXmlBaseService.default().setSelfSignCallBack(selfSignCallBack);
The priority of the single-request signature is higher than that of the key-based signature. Therefore, the configured key will not affect the setting of the single-request signature. Simply set the signature directly to the cosXmlRequest via the setSign method.
import { CosXmlBaseService, PutObjectRequest, UploadTask } from '@tencentcloud/cos';

// Any CosXmlRequest supports this method, for example, upload PutObjectRequest, download GetObjectRequest, delete DeleteObjectRequest, etc.
// The following uses upload as an example
let putRequest = new PutObjectRequest("examplebucket-1250000000", "exampleobject.txt", "Local file path");
// authorization, token, and tokenName are the single-signature information obtained in the first step "Initialize Key"
putRequest.setSign(authorization, stoken, tokenName);
let task: UploadTask = CosXmlBaseService.default().upload(putRequest);
task.start();
Initialize the default Service. Due to the risk of key leakage in this approach, be sure to replace it with the temporary key method before going live.
// Service configuration
let cosXmlServiceConfig = new CosXmlServiceConfig("ap-guangzhou");
// Initialize the default Service
CosXmlBaseService.initDefaultService( this.context.getApplicationContext(), cosXmlServiceConfig,
// The fixed key callback obtained in the first step "Initialize Key" Credential.constCredential )

Parameter Description

CosXmlServiceConfig is used to configure the COS service, and its main members are described as follows:
Parameter Name
Description
Type
Default Value
Required or Not
region
Bucket region. For details, see Regions and Access Domains
string
None.
No (or host)
protocol
Network protocol: https, http
string
https
No
connectTimeout
Connection timeout (unit: ms)
number
15 * 1000
No
readTimeout
Read timeout (unit: ms)
number
30 * 1000
No
host
Custom domain. The sdk will replace ${bucket} with the actual bucket and ${region} with the actual region.
For example: if you set the host to ${bucket}.${region}.tencent.com, and your bucket and region are bucket-1250000000 and ap-shanghai respectively, then the final request address will be
bucket-1250000000.ap-shanghai.tencent.com
string
${bucket}.cos.${region}.myqcloud.com
No (or region)
port
Set the request port.
number
None.
No
headers
Set common header.
Map<string, string>
None.
No
noSignHeaderKeys
Set unsigned header.
Set<string>
None.
No
uploadMaxConcurrentCount
Concurrent upload tasks
number
4
No
downloadMaxConcurrentCount
Concurrent download tasks
number
4
No
maxRetryCount
Maximum retry times
number
3
No
retrySleep
Retry interval, unit: ms
number
1000
No
dnsConfiguration
Specify DNS-related configurations, including custom DNS rules and the option to use DNS over HTTPS. For details, see rcp.DnsConfiguration
rcp.DnsConfiguration
None.
No

Access COS Service

PUT Object
Downloading an Object
Note:
For more complete examples, please visit GitHub to view them.

Authorization Description

When you perform authorization policy for action, see the following example.
{
"version": "2.0",
"statement": [
{
"action": [
//head operation
"name/cos:HeadObject",
//Simple upload operation
"name/cos:PutObject",
//Multipart upload: Initializing multipart upload operations
"name/cos:InitiateMultipartUpload",
//Multipart upload: Listing uploaded parts
"name/cos:ListParts",
//Multipart upload: Uploading parts operation
"name/cos:UploadPart",
//Multipart upload: Completing all multipart upload operations
"name/cos:CompleteMultipartUpload",
//Canceling multipart upload operations
"name/cos:AbortMultipartUpload"
],
"effect": "allow",
"resource": [
"qcs::cos:ap-beijing:uid/1250000000:examplebucket-1250000000/doc/*"
]
}
]
}
For more COS actions, see CAM-authorized service interfaces.

Upload Example

import { CosXmlBaseService, HttpProgress, PutObjectRequest, UploadTask, TransferConfig, CosError } from '@tencentcloud/cos';
import { CosXmlUploadTaskResult } from '@tencentcloud/cos/src/main/ets/transfer/UploadTask'

// Bucket name, which consists of bucketname-appid (appid must be included), can be viewed in the COS console. https://console.tencentcloud.com/cos5/bucket
let bucket = "examplebucket-1250000000";
//The location identifier of an object in a bucket, also known as the object key
let cosPath = "exampleobject.txt";
//Local file path
let srcPath = "Local file path";
//If there is an UploadId for initializing multipart upload, assign the corresponding _uploadId value for resuming; otherwise, assign undefined
let _uploadId: string | undefined = undefined;
// Upload configuration
let transferConfig = new TransferConfig();

let putRequest = new PutObjectRequest(bucket, cosPath, srcPath);
let task: UploadTask = CosXmlBaseService.default().upload(putRequest, _uploadId, transferConfig);
// Upload progress callback
task.onProgress = (progress: HttpProgress) => {
// progress.complete indicates the current uploaded size
// progress.target is the total size
};
// http request time-consuming callback
task.onTimeInfo = (request: CosXmlRequest, timeInfo: rcp.TimeInfo) => {
// request: current request information
// timeInfo: time-consuming information
}
task.onResult = {
// Upload success callback
onSuccess: (request, result: CosXmlUploadTaskResult) => {
// todo Logic after successful upload
},
//Upload failure callback
onFail: (request, error: CosError) => {
// todo Logic after upload failure
}
}
// Initialization complete callback
task.initCallBack = (uploadId) =>{
// uploadId for the next resumable upload
_uploadId = uploadId;
}
// Start upload
task.start();
// Pause task
// task.pause();
// Resume task
// task.resume();
// Cancel task
// task.cancel();
TransferConfig is used to configure the COS upload service. The main parameters are described as follows:
Parameter Name
Description
Type
Default Value
Required or Not
simpleUploadLimit
Simple upload limit: If the file size is less than this value, use simple upload; otherwise, use multipart upload.
number
1 * 1024 * 1024
No
sliceLength
The size of each part in multipart upload.
number
1 * 1024 * 1024
No
Note:
The advanced download interface supports resuming from breakpoints, which means it initiates a HEAD request to retrieve file information before downloading. If you are using temporary keys or accessing with a sub-account, ensure that the HeadObject permission is included in the permission list.
For more complete examples, please visit GitHub to view them.

Authorization Description

When you perform authorization policy for action, see the following example.
{
"version": "2.0",
"statement": [
{
"action": [
//head operation
"name/cos:HeadObject",
//Downloading operation
"name/cos:GetObject",
],
"effect": "allow",
"resource": [
"qcs::cos:ap-beijing:uid/1250000000:examplebucket-1250000000/doc/*"
]
}
]
}
For more COS actions, see CAM-authorized service interfaces.

Download Example

The advanced API supports pausing, resuming, and canceling download requests, and also supports the breakpoint download feature.
You only need to ensure that the bucket, cosPath, and savePath parameters match, and the SDK will resume downloading from where it left off.
import { CosXmlBaseService, HttpProgress, GetObjectRequest, DownloadTask, CosError } from '@tencentcloud/cos';
import { CosXmlDownloadTaskResult } from '@tencentcloud/cos/src/main/ets/transfer/DownloadTask'

// Bucket name, which consists of bucketname-appid (appid must be included), can be viewed in the COS console. https://console.tencentcloud.com/cos5/bucket
let bucket = "examplebucket-1250000000";
//The location identifier of an object in a bucket, also known as the object key
let cosPath = "exampleobject.txt";
// Local file download path. If the file does not exist, the sdk will automatically create it.
let downliadPath = "Local file path";

let getRequest = new GetObjectRequest(bucket, cosPath, downliadPath);
let task: DownloadTask = CosXmlBaseService.default().download(getRequest);
// Download progress callback
task.onProgress = (progress: HttpProgress) => {
// progress.complete indicates the currently downloaded size
// progress.target is the total size
};
task.onResult = {
// Download success callback
onSuccess: (request, result: CosXmlDownloadTaskResult) => {
// todo Logic after successful download
},
// Download failure callback
onFail: (request, error: CosError) => {
// todo Logic after download failure
}
}
// Start download
task.start();
// Pause task
// task.pause();
// Resume task
// task.resume();
// Cancel task
// task.cancel();

FAQs

You may encounter some common issues during use. For related solutions, see the HarmonyOS SDK FAQ.





Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback