tencent cloud

Cloud Object Storage

Release Notes and Announcements
Release Notes
Announcements
Product Introduction
Overview
Features
Use Cases
Strengths
Concepts
Regions and Access Endpoints
Specifications and Limits
Service Regions and Service Providers
Billing
Billing Overview
Billing Method
Billable Items
Free Tier
Billing Examples
Viewing and Downloading Bill
Payment Overdue
FAQs
Getting Started
Console
Getting Started with COSBrowser
User Guide
Creating Request
Bucket
Object
Data Management
Batch Operation
Global Acceleration
Monitoring and Alarms
Operations Center
Data Processing
Content Moderation
Smart Toolbox
Data Processing Workflow
Application Integration
User Tools
Tool Overview
Installation and Configuration of Environment
COSBrowser
COSCLI (Beta)
COSCMD
COS Migration
FTP Server
Hadoop
COSDistCp
HDFS TO COS
GooseFS-Lite
Online Tools
Diagnostic Tool
Use Cases
Overview
Access Control and Permission Management
Performance Optimization
Accessing COS with AWS S3 SDK
Data Disaster Recovery and Backup
Domain Name Management Practice
Image Processing
Audio/Video Practices
Workflow
Direct Data Upload
Content Moderation
Data Security
Data Verification
Big Data Practice
COS Cost Optimization Solutions
Using COS in the Third-party Applications
Migration Guide
Migrating Local Data to COS
Migrating Data from Third-Party Cloud Storage Service to COS
Migrating Data from URL to COS
Migrating Data Within COS
Migrating Data Between HDFS and COS
Data Lake Storage
Cloud Native Datalake Storage
Metadata Accelerator
GooseFS
Data Processing
Data Processing Overview
Image Processing
Media Processing
Content Moderation
File Processing Service
File Preview
Troubleshooting
Obtaining RequestId
Slow Upload over Public Network
403 Error for COS Access
Resource Access Error
POST Object Common Exceptions
API Documentation
Introduction
Common Request Headers
Common Response Headers
Error Codes
Request Signature
Action List
Service APIs
Bucket APIs
Object APIs
Batch Operation APIs
Data Processing APIs
Job and Workflow
Content Moderation APIs
Cloud Antivirus API
SDK Documentation
SDK Overview
Preparations
Android SDK
C SDK
C++ SDK
.NET(C#) SDK
Flutter SDK
Go SDK
iOS SDK
Java SDK
JavaScript SDK
Node.js SDK
PHP SDK
Python SDK
React Native SDK
Mini Program SDK
Error Codes
Harmony SDK
Endpoint SDK Quality Optimization
Security and Compliance
Data Disaster Recovery
Data Security
Cloud Access Management
FAQs
Popular Questions
General
Billing
Domain Name Compliance Issues
Bucket Configuration
Domain Names and CDN
Object Operations
Logging and Monitoring
Permission Management
Data Processing
Data Security
Pre-signed URL Issues
SDKs
Tools
APIs
Agreements
Service Level Agreement
Privacy Policy
Data Processing And Security Agreement
Contact Us
Glossary

Downloading an Object

PDF
Focus Mode
Font Size
Last updated: 2026-03-05 16:53:57

Introduction

This article introduces the sample code and description for downloading objects via the Tencent Cloud COS C++ SDK, covering four parts: high-level APIs, simple APIs, asynchronous high-level APIs, and asynchronous simple APIs.

Must-Knows

If you want to download an object, you need to have read permission for the target object: when you configure the authorization policy, set action to cos:GetObject, for more authorization, see CAM-supported business APIs.

Related Examples

Function Name
Description
Example code
high-level APIs
High-level APIs use multithreading to concurrently download multiple chunks based on range, and only support downloading to files. There are two types: one is the multithreaded version, and the other is the multithreaded resumable download version.
simple APIs
The GET Object API can implement streaming downloads and download objects to local files, but does not support the resumable download feature.
Asynchronous high-level APIs
Asynchronous high-level APIs encapsulate the high-level APIs, using multithreading to concurrently download multiple chunks based on range, and only support downloading to files. There are two types: one is the multithreaded version, and the other is the multithreaded resumable download version. They support progress callback and download status callback features.
Asynchronous simple APIs
Asynchronous high-level APIs encapsulate simple APIs, using multithreading to concurrently download multiple chunks based on range, and only support downloading to files. They support progress callback and download status callback features, but do not support multithreading and resumable download features.

Advanced API (recommended)

Note:
Only supports downloading to a file.
The high-level APIs download multiple chunks concurrently using multithreading.
The chunk size can be configured by users and defaults to 4MB.
The download thread pool size allows users to configure it, defaulting to 10.

Preliminary Preparation: Create CosAPI

Before calling the COS API, you must first create an instance of CosAPI to make subsequent call requests.
qcloud_cos::CosAPI InitCosAPI() {
uint64_t appid = 12500000000;
std::string region = "ap-guangzhou";// Region of the bucket, see https://www.tencentcloud.com/document/product/436/62?from_cn_redirect=1
std::string secret_id = "************************************"; // User's SecretId. It is recommended to use sub-account keys, with authorization following the least privilege principle to mitigate usage risks. For information on how to obtain sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
std::string secret_key = "************************************"; // User's SecretKey. It is recommended to use sub-account keys, with authorization following the least privilege principle to mitigate usage risks. For information on how to obtain sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
qcloud_cos::CosConfig config(appid, secret_id, secret_key, region);
qcloud_cos::CosAPI cos_tmp(config);
return cos_tmp;
}

Preparations: Using Temporary Keys to Create CosAPI

To access COS with a temporary key, you need to create a CosAPI instance using the temporary key.
qcloud_cos::CosAPI InitCosAPI() {
// You need to have obtained the temporary key results: tmp_secret_id, tmp_secret_key,
// For generating temporary keys, see https://www.tencentcloud.com/document/product/436/14048?from_cn_redirect=1#cos-sts-sdk
uint64_t appid = 12500000000;
std::string region = "ap-guangzhou";
std::string tmp_secret_id = "************************************";
std::string tmp_secret_key = "************************************";
std::string tmp_token = "token";
qcloud_cos::CosConfig config(appid, tmp_secret_id, tmp_secret_key, region);
config.SetTmpToken(tmp_token);
qcloud_cos::CosAPI cos_tmp(config);
return cos_tmp;
}

Use Case:Multithreaded Download API

Note:
This Demo demonstrates how to download objects using the multi-threaded version of the advanced API.
Only supports downloading to a file.
The download thread pool size and chunk size can be set globally. This download thread pool is dedicated to each download.
Method Prototype
CosResult CosAPI::MultiGetObject(const MultiGetObjectReq& req, MultiGetObjectResp* resp)
Request Example
void MultiGetObjectDemo(qcloud_cos::CosAPI& cos) {
std::string file_path = "test_file/big_file.txt";
std::string object_name = "big_file.txt";
// This configuration is global. Once explicitly set, all subsequent APIs involving multi-threaded downloads will use this configuration.
CosSysConfig::SetDownThreadPoolSize(10); // Download thread pool size, defaulting to 10
CosSysConfig::SetDownSliceSize(4 * 1024 * 1024); // Download range size, default 4M
qcloud_cos::MultiGetObjectReq req(bucket_name, object_name, file_path);
qcloud_cos::MultiGetObjectResp resp;
qcloud_cos::CosResult result = cos.MultiGetObject(req, &resp);
std::cout << "===================GetObjectResponse=====================" << std::endl;
PrintResult(result, resp);
std::cout << "=========================================================" << std::endl;
}
Parameter Descriptions
Parameter Name
Description
Type
req
Download file request
MultiGetObjectReq
resp
File download response
MultiGetObjectResp
MultiGetObjectReq Member or Function Description:
Member or Function
Description
Parameter Type
bucket_name
Bucket name, which can be set via the constructor or set method.
The naming format for buckets is BucketName-APPID. For details, see Naming Conventions
string
object_name
Object key (Key), which can be set via the constructor or set method.
is the unique identifier of the object in the bucket. For example, in the object access domain name examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/picture.jpg, the object key is doc/picture.jpg. For details, see Object Key
string
local_file_path
Local file path, which can be set via the constructor or set method.
string
SetTrafficLimit
Used for traffic control of download objects, unit: bit/s. By default, no traffic control is performed.
string
MultiGetObjectResp Member Function Description:
Member functions
Description
Return Type
GetXCosMetas
Obtain the custom metadata map.
map<std::string, std::string>
GetXCosMeta
Obtain the specified custom metadata.
string
GetXCosServerSideEncryption
Obtain the server-side encryption algorithm used
string
GetEtag
Obtain the Etag of the stored download object.
string
GetXCosRequestId
Obtain the request ID.
string

The CosSysConfig class is used for related configurations. In this sample, the main member functions are as follows:
Member functions
Description
Parameter Type
SetDownSliceSize
Set the part size for part download, unit: byte (Byte), default: 4MB.
The setting method is CosSysConfig::SetDownSliceSize(4 * 1024 * 1024).
uint64_t
SetDownThreadPoolSize
Set the download thread pool size, defaulting to 10.
The setting method is CosSysConfig::SetDownThreadPoolSize(10).
unsigned
Returning Description
CosResult main member functions are as follows:
Member functions
Description
Return Type
IsSucc
Indicates whether the operation is successful; returns true for success, false for failure.
bool
GetHttpStatus
Obtains the HTTP status code.
int
GetErrorCode
Obtain the error code when the request fails.
string
GetErrorMsg
Obtain the error message when the request fails.
string
GetXCosRequestId
Obtain the request ID.
string
Usage examples for CosResult are as follows. Users may choose to utilize them based on their needs:
void PrintResult(const qcloud_cos::CosResult& result, const qcloud_cos::BaseResp& resp) {
if (result.IsSucc()) {
std::cout << "Request Succ." << std::endl;
std::cout << resp.DebugString() << std::endl;
} else {
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "HttpStatus=" << result.GetHttpStatus() << std::endl;
std::cout << "ErrorCode=" << result.GetErrorCode() << std::endl;
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "ResourceAddr=" << result.GetResourceAddr() << std::endl;
std::cout << "XCosRequestId=" << result.GetXCosRequestId() << std::endl;
std::cout << "XCosTraceId=" << result.GetXCosTraceId() << std::endl;
}
}

Use Case: Multithreaded Breakpoint Download API

Note:
This Demo demonstrates how to use the advanced API for multi-threaded resumable download of objects.
Only supports downloading to a file.
The download thread pool size and chunk size can be set globally. This download thread pool is dedicated to each download.
Method Prototype
CosResult CosAPI::ResumableGetObject(const GetObjectByFileReq& req, GetObjectByFileResp* resp)
Request Example
void ResumableGetObjectDemo(qcloud_cos::CosAPI& cos) {
std::string file_path = "test_file/big_file.txt";
std::string object_name = "big_file.txt";

qcloud_cos::GetObjectByFileReq req(bucket_name, object_name, file_path);
qcloud_cos::GetObjectByFileResp resp;

CosResult result = cos.ResumableGetObject(req, &resp);
std::cout << "===================ResumableGetObject====================" << std::endl;
PrintResult(result, resp);
std::cout << "=========================================================" << std::endl;
}
Parameter Descriptions
Parameter Name
Description
Type
req
Download file request
GetObjectByFileReq
resp
File download response
GetObjectByFileResp
GetObjectByFileReq Member or Function Description:
Member or Function
Description
Parameter Type
bucket_name
Bucket name, which can be set via the constructor or set method.
The naming format for buckets is BucketName-APPID. For details, see Naming Conventions
string
object_name
Object key (Key), which can be set via the constructor or set method.
is the unique identifier of the object in the bucket. For example, in the object access domain name examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/picture.jpg, the object key is doc/picture.jpg. For details, see Object Key
string
local_file_path
Local file path, which can be set via the constructor or set method.
string
SetTrafficLimit
Used for traffic control of download objects, unit: bit/s. By default, no traffic control is performed.
uint64_t
GetObjectByFileResp Member Function Description:
Member functions
Description
Return Type
GetXCosMetas
Obtain the custom metadata map.
map<std::string, std::string>
GetXCosMeta
Obtain the specified custom metadata.
string
GetXCosServerSideEncryption
Obtain the server-side encryption algorithm used
string
GetEtag
Obtain the Etag of the stored download object.
string
GetXCosRequestId
Obtain the request ID.
string
Returning Description
CosResult main member functions are as follows:
Member functions
Description
Return Type
IsSucc
Indicates whether the operation is successful; returns true for success, false for failure.
bool
GetHttpStatus
Obtain the HTTP status code.
int
GetErrorCode
The error code can be obtained when the request fails.
string
GetErrorMsg
Obtain the error message when the request fails.
string
GetXCosRequestId
Obtain the request ID.
string
Usage examples for CosResult are as follows. Users may choose to utilize them based on their needs:
void PrintResult(const qcloud_cos::CosResult& result, const qcloud_cos::BaseResp& resp) {
if (result.IsSucc()) {
std::cout << "Request Succ." << std::endl;
std::cout << resp.DebugString() << std::endl;
} else {
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "HttpStatus=" << result.GetHttpStatus() << std::endl;
std::cout << "ErrorCode=" << result.GetErrorCode() << std::endl;
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "ResourceAddr=" << result.GetResourceAddr() << std::endl;
std::cout << "XCosRequestId=" << result.GetXCosRequestId() << std::endl;
std::cout << "XCosTraceId=" << result.GetXCosTraceId() << std::endl;
}
}

Simple APIs

Preliminary Preparation: Create CosAPI

Before calling the COS API, you must first create an instance of CosAPI to make subsequent call requests.
qcloud_cos::CosAPI InitCosAPI() {
uint64_t appid = 12500000000;
std::string region = "ap-guangzhou";// Region of the bucket, see https://www.tencentcloud.com/document/product/436/62?from_cn_redirect=1
std::string secret_id = "************************************"; // User's SecretId. It is recommended to use sub-account keys, with authorization following the least privilege principle to mitigate usage risks. For information on how to obtain sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
std::string secret_key = "************************************"; // User's SecretKey. It is recommended to use sub-account keys, with authorization following the least privilege principle to mitigate usage risks. For information on how to obtain sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
qcloud_cos::CosConfig config(appid, secret_id, secret_key, region);
qcloud_cos::CosAPI cos_tmp(config);
return cos_tmp;
}

Preparations: Using Temporary Keys to Create CosAPI

To access COS with a temporary key, you need to create a CosAPI instance using the temporary key.
qcloud_cos::CosAPI InitCosAPI() {
// You need to have obtained the temporary key results: tmp_secret_id, tmp_secret_key,
// For generating temporary keys, see https://www.tencentcloud.com/document/product/436/14048?from_cn_redirect=1#cos-sts-sdk
uint64_t appid = 12500000000;
std::string region = "ap-guangzhou";
std::string tmp_secret_id = "************************************";
std::string tmp_secret_key = "************************************";
std::string tmp_token = "token";
qcloud_cos::CosConfig config(appid, tmp_secret_id, tmp_secret_key, region);
config.SetTmpToken(tmp_token);
qcloud_cos::CosAPI cos_tmp(config);
return cos_tmp;
}

Use Case: Download to Local File

Note:
This Demo demonstrates how to download objects to local files using the COS C++ SDK.
Method Prototype
CosResult CosAPI::GetObject(const GetObjectByFileReq& req, GetObjectByFileResp* resp)
Request Example
void GetObjectByFileDemo(qcloud_cos::CosAPI& cos) {
std::string object_name = "test_src.txt";
std::string file_path = "./test_file/text2.txt";
qcloud_cos::GetObjectByFileReq req(bucket_name, object_name, file_path);
// Download objects with rate limiting. The default unit is bit/s, and the rate limit value can be set in the range of 819200 - 838860800
// uint64_t traffic_limit = 0;
// req.SetTrafficLimit(traffic_limit);
qcloud_cos::GetObjectByFileResp resp;
qcloud_cos::CosResult result = cos.GetObject(req, &resp);
std::cout << "===================GetObjectResponse=====================" << std::endl;
PrintResult(result, resp);
std::cout << "=========================================================" << std::endl;
}
Parameter Descriptions
Parameter Name
Description
Type
req
Download file request
GetObjectByFileReq
resp
File download response
GetObjectByFileResp
GetObjectByFileReq Member or Function Description:
Member or Function
Description
Parameter Type
bucket_name
Bucket name, which can be set via the constructor or set method.
The naming format for buckets is BucketName-APPID. For details, see Naming Conventions
string
object_name
Object key (Key), which can be set via the constructor or set method.
is the unique identifier of the object in the bucket. For example, in the object access domain name examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/picture.jpg, the object key is doc/picture.jpg. For details, see Object Key
string
local_file_path
Local file path, which can be set via the constructor or set method.
string
SetTrafficLimit
Set single-connection speed limit. The setting method is req.SetTrafficLimit(819200). The default unit is bit/s, and the speed limit value can be set in the range of 819200 - 838860800.
uint64_t
GetObjectByFileResp Member Function Description:
Member functions
Description
Return Type
GetXCosMetas
Obtain the custom metadata map
map<std::string, std::string>
GetXCosMeta
Obtain the specified custom metadata.
string
GetXCosServerSideEncryption
Obtain the server-side encryption algorithm used
string
GetEtag
Obtain the Etag of the stored download object.
string
GetXCosRequestId
Obtain the request ID.
string
Returning Description
CosResult main member functions are as follows:
Member functions
Description
Return Type
IsSucc
Indicates whether the operation is successful; returns true for success, false for failure.
bool
GetHttpStatus
Obtain the HTTP status code.
int
GetErrorCode
The error code can be obtained when the request fails.
string
GetErrorMsg
Obtain the error message when the request fails.
string
GetXCosRequestId
Obtain the request ID.
string
Usage examples for CosResult are as follows. Users may choose to utilize them based on their needs:
void PrintResult(const qcloud_cos::CosResult& result, const qcloud_cos::BaseResp& resp) {
if (result.IsSucc()) {
std::cout << "Request Succ." << std::endl;
std::cout << resp.DebugString() << std::endl;
} else {
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "HttpStatus=" << result.GetHttpStatus() << std::endl;
std::cout << "ErrorCode=" << result.GetErrorCode() << std::endl;
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "ResourceAddr=" << result.GetResourceAddr() << std::endl;
std::cout << "XCosRequestId=" << result.GetXCosRequestId() << std::endl;
std::cout << "XCosTraceId=" << result.GetXCosTraceId() << std::endl;
}
}

Use Case: Download to Stream

Note:
This Demo demonstrates how to use the COS C++ SDK to download objects to a stream.
Method Prototype
CosResult CosAPI::GetObject(const GetObjectByStreamReq& req, GetObjectByStreamResp* resp)
Request Example
void GetObjectByStreamDemo(qcloud_cos::CosAPI& cos) {
std::string object_name = "test.txt";
std::ostringstream os;
qcloud_cos::GetObjectByStreamReq req(bucket_name, object_name, os);
// Download objects with rate limiting. The default unit is bit/s, and the rate limit value can be set in the range of 819200 - 838860800
// uint64_t traffic_limit = 0;
// req.SetTrafficLimit(traffic_limit);
qcloud_cos::GetObjectByStreamResp resp;
qcloud_cos::CosResult result = cos.GetObject(req, &resp);
std::cout << "===================GetObjectResponse=====================" << std::endl;
PrintResult(result, resp);
std::cout << "=========================================================" << std::endl;
std::cout << os.str() << std::endl;
}
Parameter Descriptions
Parameter Name
Description
Type
req
Download file request
GetObjectByStreamReq
resp
File download response
GetObjectByStreamResp
GetObjectByStreamReq Member or Function Description:
Member or Function
Description
Parameter Type
bucket_name
Bucket name, which can be set via the constructor or set method.
The naming format for buckets is BucketName-APPID. For details, see Naming Conventions
string
object_name
Object key (Key), which can be set via the constructor or set method.
is the unique identifier of the object in the bucket. For example, in the object access domain name examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/picture.jpg, the object key is doc/picture.jpg. For details, see Object Key
string
os
Output stream, which can be set via the constructor.
ostream
SetTrafficLimit
Set single-connection speed limit. The setting method is req.SetTrafficLimit(819200). The default unit is bit/s, and the speed limit value can be set in the range of 819200 - 838860800.
uint64_t
GetObjectByStreamResp Member Function Description:
Member functions
Description
Return Type
GetXCosMetas
Obtain the custom metadata map.
map<std::string, std::string>
GetXCosMeta
Obtain the specified custom metadata.
string
GetXCosServerSideEncryption
Obtain the server-side encryption algorithm used
string
GetEtag
Obtain the Etag of the stored download object.
string
GetXCosRequestId
Obtain the request ID.
string
Returning Description
CosResult main member functions are as follows:
Member functions
Description
Return Type
IsSucc
Indicates whether the operation is successful; returns true for success, false for failure.
bool
GetHttpStatus
Obtain the HTTP status code.
int
GetErrorCode
The error code can be obtained when the request fails.
string
GetErrorMsg
Obtain the error message when the request fails.
string
GetXCosRequestId
Obtain the request ID.
string
Usage examples for CosResult are as follows. Users may choose to utilize them based on their needs:
void PrintResult(const qcloud_cos::CosResult& result, const qcloud_cos::BaseResp& resp) {
if (result.IsSucc()) {
std::cout << "Request Succ." << std::endl;
std::cout << resp.DebugString() << std::endl;
} else {
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "HttpStatus=" << result.GetHttpStatus() << std::endl;
std::cout << "ErrorCode=" << result.GetErrorCode() << std::endl;
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "ResourceAddr=" << result.GetResourceAddr() << std::endl;
std::cout << "XCosRequestId=" << result.GetXCosRequestId() << std::endl;
std::cout << "XCosTraceId=" << result.GetXCosTraceId() << std::endl;
}
}

Asynchronous Advanced API

Note:
It only supports downloading to files.
Download multiple chunks concurrently using multithreading.
The chunk size can be configured by users and defaults to 4MB.
The download thread pool size allows users to configure it, defaulting to 10.
The asynchronous thread pool size allows users to configure it, defaulting to 2.

Preliminary Preparation: Create CosAPI

Before calling the COS API, you must first create an instance of CosAPI to make subsequent call requests.
qcloud_cos::CosAPI InitCosAPI() {
uint64_t appid = 12500000000;
std::string region = "ap-guangzhou";// Region of the bucket, see https://www.tencentcloud.com/document/product/436/62?from_cn_redirect=1
std::string secret_id = "************************************"; // User's SecretId. It is recommended to use sub-account keys, with authorization following the least privilege principle to mitigate usage risks. For information on how to obtain sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
std::string secret_key = "************************************"; // User's SecretKey. It is recommended to use sub-account keys, with authorization following the least privilege principle to mitigate usage risks. For information on how to obtain sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
qcloud_cos::CosConfig config(appid, secret_id, secret_key, region);
qcloud_cos::CosAPI cos_tmp(config);
return cos_tmp;
}

Preparations: Using Temporary Keys to Create CosAPI

To access COS with a temporary key, you need to create a CosAPI instance using the temporary key.
qcloud_cos::CosAPI InitCosAPI() {
// You need to have obtained the temporary key results: tmp_secret_id, tmp_secret_key,
// For generating temporary keys, see https://www.tencentcloud.com/document/product/436/14048?from_cn_redirect=1#cos-sts-sdk
uint64_t appid = 12500000000;
std::string region = "ap-guangzhou";
std::string tmp_secret_id = "************************************";
std::string tmp_secret_key = "************************************";
std::string tmp_token = "token";
qcloud_cos::CosConfig config(appid, tmp_secret_id, tmp_secret_key, region);
config.SetTmpToken(tmp_token);
qcloud_cos::CosAPI cos_tmp(config);
return cos_tmp;
}

Use Case: Asynchronous Multi-Threaded Download API

Note:
This Demo demonstrates how to use the asynchronous multi-threaded download API for object downloads. It includes examples of progress callbacks and download status callbacks.
Only file downloads are supported, and stream-based downloads are not supported.
The download thread pool size and chunk size can be set globally. This download thread pool is dedicated to each download.
The asynchronous thread pool size can be set globally. This thread pool is globally shared and used for asynchronous scheduling.

Method Prototype

SharedAsyncContext CosAPI::AsyncMultiGetObject(const AsyncMultiGetObjectReq& req)

Request Example

/*
* This method is a sample progress callback for asynchronous object download
*/
void ProgressCallback(uint64_t transferred_size, uint64_t total_size, void* user_data) {
qcloud_cos::ObjectReq* req = static_cast<qcloud_cos::ObjectReq*>(user_data);
if (0 == transferred_size % 1048576) {
std::cout << "ObjectName:" << req->GetObjectName() << ", TranferedSize:" << transferred_size << ",TotalSize:" << total_size << std::endl;
}
}
/*
* This method is a sample of a completion callback for asynchronous object download
*/
void GetObjectAsyncDoneCallback(const SharedAsyncContext& context, void* user_data) {
UNUSED_PARAM(user_data)
std::cout << "AsyncMultiGetObjectDemoCallback, BucketName:"
<< context->GetBucketName()
<< ", ObjectName:" << context->GetObjectName()
<< ", LocalFile:" << context->GetLocalFilePath() << std::endl;
// The response corresponding to qcloud_cos::MultiGetObjectReq is qcloud_cos::GetObjectByFileResp
if (context->GetResult().IsSucc()) {
// Obtain the response
std::cout << "GetObject succeed" << std::endl;
std::cout << "Result:" << context->GetResult().DebugString() << std::endl;
AsyncResp resp = context->GetAsyncResp();
std::cout << "ETag:" << resp.GetEtag() << std::endl;
std::cout << "Crc64:" << resp.GetXCosHashCrc64Ecma() << std::endl;
} else {
std::cout << "GetObject failed" << std::endl;
std::cout << "ErrorMsg:" << context->GetResult().GetErrorMsg() << std::endl;
}
}

void AsyncMultiGetObjectDemo(qcloud_cos::CosAPI& cos) {
CosSysConfig::SetAsynThreadPoolSize(2); // Set asynchronous thread pool size, defaulting to 2

std::string local_file = "test_file/big_file.txt";
std::string object_name = "big_file.txt";
qcloud_cos::AsyncMultiGetObjectReq req(bucket_name, object_name, local_file);
// Set the download progress callback
req.SetTransferProgressCallback(&ProgressCallback);
// Set the download status callback
req.SetDoneCallback(&GetObjectAsyncDoneCallback);
// Set private data, which corresponds to user_data in the callback
req.SetUserData(&req);

// Begin download
SharedAsyncContext context = cos.AsyncMultiGetObject(req);

std::cout << "===================AsyncMultiGetObject======================" << std::endl;
// Wait for the download to complete
std::cout << "wait finish..." << std::endl;
context->WaitUntilFinish();
// Check the result
if (context->GetResult().IsSucc()) {
// Obtain the response
std::cout << "AsyncMultiGetObject succeed" << std::endl;
std::cout << "Result:" << context->GetResult().DebugString() << std::endl;
AsyncResp resp = context->GetAsyncResp();
std::cout << "ETag:" << resp.GetEtag() << std::endl;
std::cout << "Crc64:" << resp.GetXCosHashCrc64Ecma() << std::endl;
} else {
std::cout << "AsyncMultiGetObject failed" << std::endl;
std::cout << "ErrorMsg:" << context->GetResult().GetErrorMsg() << std::endl;
}
std::cout << "============================================================" << std::endl;
}

Parameter Description

Parameter Name
Description
Type
req
Download file request
AsyncMultiGetObjectReq
AsyncMultiGetObjectReq member or function description:
Member or Function
Description
Parameter Type
bucket_name
Bucket name, which can be set via the constructor or set method.
The naming format for buckets is BucketName-APPID. For details, see Naming Conventions
string
object_name
Object key (Key), which can be set via the constructor or set method.
is the unique identifier of the object in the bucket. For example, in the object access domain name examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/picture.jpg, the object key is doc/picture.jpg. For details, see Object Key
string
local_file_path
Local file path, which can be set via the constructor or set method.
string
SetTransferProgressCallback
Set the download progress callback method
TransferProgressCallback
SetDoneCallback
Set the download progress status method
DoneCallback
The CosSysConfig class is used for related configurations. In this sample, the main member functions are as follows:
Member functions
Description
Parameter Type
SetAsynThreadPoolSize
Set the size of the asynchronous thread pool, defaulting to 2.
The setting method is CosSysConfig::SetAsyncThreadPoolSize(2).
unsigned

Returning Description

The main member functions of context are described as follows:
Member functions
Description
Return Type
WaitUntilFinish
Wait for the download to complete.
None
GetResult
Obtain the Result.
CosResult
GetAsyncResp
Obtain the Resp response.
AsyncResp
The main member functions of AsyncResp are described as follows:
Member functions
Description
Return Type
GetXCosHashCrc64Ecma
Obtain the CRC64 of the stored download object.
string
GetEtag
Obtain the Etag of the stored download object.
string
GetXCosRequestId
Obtain the request ID.
string
CosResult main member functions are as follows:
Member functions
Description
Return Type
IsSucc
Indicates whether the operation is successful; returns true for success, false for failure.
bool
GetHttpStatus
Obtains the HTTP status code.
int
GetErrorCode
Obtain the error code when the request fails.
string
GetErrorMsg
Obtain the error message when the request fails.
string
GetXCosRequestId
Obtain the request ID.
string
Usage examples for CosResult are as follows. Users may choose to utilize them based on their needs:
void PrintResult(const qcloud_cos::CosResult& result, const qcloud_cos::BaseResp& resp) {
if (result.IsSucc()) {
std::cout << "Request Succ." << std::endl;
std::cout << resp.DebugString() << std::endl;
} else {
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "HttpStatus=" << result.GetHttpStatus() << std::endl;
std::cout << "ErrorCode=" << result.GetErrorCode() << std::endl;
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "ResourceAddr=" << result.GetResourceAddr() << std::endl;
std::cout << "XCosRequestId=" << result.GetXCosRequestId() << std::endl;
std::cout << "XCosTraceId=" << result.GetXCosTraceId() << std::endl;
}
}

Use Case: Asynchronous Multi-threaded Resumable Download API

Note:
This Demo demonstrates how to use the asynchronous multi-threaded resumable download API to download objects, and includes examples of progress callbacks and download status callbacks.
Only file downloads are supported, stream-based downloads are not supported, and the resumable download feature is supported.
The download thread pool size and chunk size can be set globally. This download thread pool is dedicated to each download.
The asynchronous thread pool size can be set globally. This thread pool is globally shared and used for asynchronous scheduling.

Method Prototype

SharedAsyncContext CosAPI::AsyncResumableGetObject(const AsyncGetObjectReq& req)

Request Example

/*
* This method is a sample progress callback for asynchronous object download
*/
void ProgressCallback(uint64_t transferred_size, uint64_t total_size, void* user_data) {
qcloud_cos::ObjectReq* req = static_cast<qcloud_cos::ObjectReq*>(user_data);
if (0 == transferred_size % 1048576) {
std::cout << "ObjectName:" << req->GetObjectName() << ", TranferedSize:" << transferred_size << ",TotalSize:" << total_size << std::endl;
}
}
/*
* This method is a sample of a completion callback for asynchronous object download
*/
void GetObjectAsyncDoneCallback(const SharedAsyncContext& context, void* user_data) {
UNUSED_PARAM(user_data)
std::cout << "AsyncResumableGetObjectDemoCallback, BucketName:"
<< context->GetBucketName()
<< ", ObjectName:" << context->GetObjectName()
<< ", LocalFile:" << context->GetLocalFilePath() << std::endl;
// The response corresponding to qcloud_cos::MultiGetObjectReq is qcloud_cos::GetObjectByFileResp
if (context->GetResult().IsSucc()) {
// Obtain the response
std::cout << "GetObject succeed" << std::endl;
std::cout << "Result:" << context->GetResult().DebugString() << std::endl;
AsyncResp resp = context->GetAsyncResp();
std::cout << "ETag:" << resp.GetEtag() << std::endl;
std::cout << "Crc64:" << resp.GetXCosHashCrc64Ecma() << std::endl;
} else {
std::cout << "GetObject failed" << std::endl;
std::cout << "ErrorMsg:" << context->GetResult().GetErrorMsg() << std::endl;
}
}

void AsyncResumableGetObjectDemo(qcloud_cos::CosAPI& cos) {
std::string local_file = "test_file/big_file.txt";
std::string object_name = "big_file.txt";
qcloud_cos::AsyncGetObjectReq req(bucket_name, object_name, local_file);
// Set the download progress callback
req.SetTransferProgressCallback(&ProgressCallback);
// Set the download status callback
req.SetDoneCallback(&GetObjectAsyncDoneCallback);
// Set private data, which corresponds to user_data in the callback
req.SetUserData(&req);
// Begin download
SharedAsyncContext context = cos.AsyncResumableGetObject(req);

std::cout << "===================AsyncResumableGetObject======================" << std::endl;
// Wait for the download to complete
std::cout << "wait finish..." << std::endl;
context->WaitUntilFinish();
// Check the result
if (context->GetResult().IsSucc()) {
// Obtain the response
std::cout << "AsyncResumableGetObject succeed" << std::endl;
std::cout << "Result:" << context->GetResult().DebugString() << std::endl;
AsyncResp resp = context->GetAsyncResp();
std::cout << "ETag:" << resp.GetEtag() << std::endl;
std::cout << "Crc64:" << resp.GetXCosHashCrc64Ecma() << std::endl;
} else {
std::cout << "AsyncResumableGetObject failed" << std::endl;
std::cout << "ErrorMsg:" << context->GetResult().GetErrorMsg() << std::endl;
}
std::cout << "================================================================" << std::endl;
}

Parameter Description

Parameter Name
Description
Type
req
Download file request
AsyncGetObjectReq
AsyncGetObjectReq member or function description:
Member or Function
Description
Parameter Type
bucket_name
Bucket name, which can be set via the constructor or set method.
The naming format for buckets is BucketName-APPID. For details, see Naming Conventions
string
object_name
Object key (Key), which can be set via the constructor or set method.
is the unique identifier of the object in the bucket. For example, in the object access domain name examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/picture.jpg, the object key is doc/picture.jpg. For details, see Object Key
string
local_file_path
Local file path, which can be set via the constructor or set method.
string
SetTransferProgressCallback
Set the download progress callback method.
TransferProgressCallback
SetDoneCallback
Set the download progress status method.
DoneCallback
The CosSysConfig class is used for related configurations. In this sample, the main member functions are as follows:
Member functions
Description
Parameter Type
SetAsynThreadPoolSize
Set the size of the asynchronous thread pool, defaulting to 2.
The setting method is CosSysConfig::SetAsyncThreadPoolSize(2).
unsigned

Returning Description

The main member functions of context are described as follows:
Member functions
Description
Return Type
WaitUntilFinish
Wait for the download to complete.
None
GetResult
Obtain the Result.
CosResult
GetAsyncResp
Obtain the Resp response.
AsyncResp
The main member functions of AsyncResp are described as follows:
Member functions
Description
Return Type
GetXCosHashCrc64Ecma
Obtain the CRC64 of the stored download object.
string
GetEtag
Obtain the Etag of the stored download object.
string
GetXCosRequestId
Obtain the request ID.
string
CosResult main member functions are as follows:
Member functions
Description
Return Type
IsSucc
Indicates whether the operation is successful; returns true for success, false for failure.
bool
GetHttpStatus
Obtains the HTTP status code.
int
GetErrorCode
Obtain the error code when the request fails.
string
GetErrorMsg
Obtain the error message when the request fails.
string
GetXCosRequestId
Obtain the request ID.
string
Usage examples for CosResult are as follows. Users may choose to utilize them based on their needs:
void PrintResult(const qcloud_cos::CosResult& result, const qcloud_cos::BaseResp& resp) {
if (result.IsSucc()) {
std::cout << "Request Succ." << std::endl;
std::cout << resp.DebugString() << std::endl;
} else {
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "HttpStatus=" << result.GetHttpStatus() << std::endl;
std::cout << "ErrorCode=" << result.GetErrorCode() << std::endl;
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "ResourceAddr=" << result.GetResourceAddr() << std::endl;
std::cout << "XCosRequestId=" << result.GetXCosRequestId() << std::endl;
std::cout << "XCosTraceId=" << result.GetXCosTraceId() << std::endl;
}
}

Asynchronous Simple API

Preliminary Preparation: Create CosAPI

Before calling the COS API, you must first create an instance of CosAPI to make subsequent call requests.
qcloud_cos::CosAPI InitCosAPI() {
uint64_t appid = 12500000000;
std::string region = "ap-guangzhou";// Region of the bucket, see https://www.tencentcloud.com/document/product/436/62?from_cn_redirect=1
std::string secret_id = "************************************"; // User's SecretId. It is recommended to use sub-account keys, with authorization following the least privilege principle to mitigate usage risks. For information on how to obtain sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
std::string secret_key = "************************************"; // User's SecretKey. It is recommended to use sub-account keys, with authorization following the least privilege principle to mitigate usage risks. For information on how to obtain sub-account keys, see https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1
qcloud_cos::CosConfig config(appid, secret_id, secret_key, region);
qcloud_cos::CosAPI cos_tmp(config);
return cos_tmp;
}

Preparations: Using Temporary Keys to Create CosAPI

To access COS with a temporary key, you need to create a CosAPI instance using the temporary key.
qcloud_cos::CosAPI InitCosAPI() {
// You need to have obtained the temporary key results: tmp_secret_id, tmp_secret_key,
// For generating temporary keys, see https://www.tencentcloud.com/document/product/436/14048?from_cn_redirect=1#cos-sts-sdk
uint64_t appid = 12500000000;
std::string region = "ap-guangzhou";
std::string tmp_secret_id = "************************************";
std::string tmp_secret_key = "************************************";
std::string tmp_token = "token";
qcloud_cos::CosConfig config(appid, tmp_secret_id, tmp_secret_key, region);
config.SetTmpToken(tmp_token);
qcloud_cos::CosAPI cos_tmp(config);
return cos_tmp;
}

Use Case: Download File to Local

Note:
This Demo demonstrates how to asynchronously download objects to local files using the COS C++ SDK.
This sample includes progress callback and download status callback.

Method Prototype

SharedAsyncContext CosAPI::AsyncGetObject(const AsyncGetObjectReq& req)

Request Example

/*
* This method is a sample progress callback for asynchronous object download
*/
void ProgressCallback(uint64_t transferred_size, uint64_t total_size, void* user_data) {
qcloud_cos::ObjectReq* req = static_cast<qcloud_cos::ObjectReq*>(user_data);
if (0 == transferred_size % 1048576) {
std::cout << "ObjectName:" << req->GetObjectName() << ", TranferedSize:" << transferred_size << ",TotalSize:" << total_size << std::endl;
}
}
/*
* This method is a sample of a completion callback for asynchronous object download
*/
void GetObjectAsyncDoneCallback(const SharedAsyncContext& context, void* user_data) {
UNUSED_PARAM(user_data)
std::cout << "AsyncGetObjectDemoCallback, BucketName:"
<< context->GetBucketName()
<< ", ObjectName:" << context->GetObjectName()
<< ", LocalFile:" << context->GetLocalFilePath() << std::endl;
// The response corresponding to qcloud_cos::MultiGetObjectReq is qcloud_cos::GetObjectByFileResp
if (context->GetResult().IsSucc()) {
// Obtain the response
std::cout << "GetObject succeed" << std::endl;
std::cout << "Result:" << context->GetResult().DebugString() << std::endl;
AsyncResp resp = context->GetAsyncResp();
std::cout << "ETag:" << resp.GetEtag() << std::endl;
std::cout << "Crc64:" << resp.GetXCosHashCrc64Ecma() << std::endl;
} else {
std::cout << "GetObject failed" << std::endl;
std::cout << "ErrorMsg:" << context->GetResult().GetErrorMsg() << std::endl;
}
}

void AsyncGetObjectDemo(qcloud_cos::CosAPI& cos) {
std::string local_file = "test_file/text.txt";
std::string object_name = "text.txt";
qcloud_cos::AsyncGetObjectReq req(bucket_name, object_name, local_file);
req.SetRecvTimeoutInms(1000 * 60);
// Set the download progress callback
req.SetTransferProgressCallback(&ProgressCallback);
// Set the download status callback
req.SetDoneCallback(&GetObjectAsyncDoneCallback);
// Set private data, which corresponds to user_data in the callback
req.SetUserData(&req);
// Begin download
SharedAsyncContext context = cos.AsyncGetObject(req);
std::cout << "===================AsyncGetObject======================" << std::endl;
// Wait for the download to complete
std::cout << "wait finish..." << std::endl;
context->WaitUntilFinish();
// Check the result
if (context->GetResult().IsSucc()) {
// Obtain the response
std::cout << "AsyncGetObject succeed" << std::endl;
std::cout << "Result:" << context->GetResult().DebugString() << std::endl;
AsyncResp resp = context->GetAsyncResp();
std::cout << "ETag:" << resp.GetEtag() << std::endl;
std::cout << "Crc64:" << resp.GetXCosHashCrc64Ecma() << std::endl;
} else {
std::cout << "AsyncGetObject failed" << std::endl;
std::cout << "ErrorMsg:" << context->GetResult().GetErrorMsg() << std::endl;
}
std::cout << "=======================================================" << std::endl;
}

Parameter Description

Parameter Name
Description
Type
req
Download file request
AsyncGetObjectReq
AsyncGetObjectReq member or function description:
Member or Function
Description
Parameter Type
bucket_name
Bucket name, which can be set via the constructor or set method.
The naming format for buckets is BucketName-APPID. For details, see Naming Conventions
string
object_name
Object key (Key), which can be set via the constructor or set method.
is the unique identifier of the object in the bucket. For example, in the object access domain name examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/picture.jpg, the object key is doc/picture.jpg. For details, see Object Key
string
local_file_path
Local file path, which can be set via the constructor or set method.
string
SetTransferProgressCallback
Set the download progress callback method.
TransferProgressCallback
SetDoneCallback
Set the download progress status method.
DoneCallback

Returning Description

The main member functions of context are described as follows:
Member functions
Description
Return Type
WaitUntilFinish
Wait for the download to complete.
None
GetResult
Obtain the Result.
CosResult
GetAsyncResp
Obtain the Resp response.
AsyncResp
The main member functions of AsyncResp are described as follows:
Member functions
Description
Return Type
GetXCosHashCrc64Ecma
Obtain the CRC64 of the stored download object.
string
GetEtag
Obtain the Etag of the stored download object.
string
GetXCosRequestId
Obtain the request ID.
string
CosResult main member functions are as follows:
Member functions
Description
Return Type
IsSucc
Indicates whether the operation is successful; returns true for success, false for failure.
bool
GetHttpStatus
Obtain the HTTP status code.
int
GetErrorCode
The error code can be obtained when the request fails.
string
GetErrorMsg
Obtain the error message when the request fails.
string
GetXCosRequestId
Obtain the request ID.
string
Usage examples for CosResult are as follows. Users may choose to utilize them based on their needs:
void PrintResult(const qcloud_cos::CosResult& result, const qcloud_cos::BaseResp& resp) {
if (result.IsSucc()) {
std::cout << "Request Succ." << std::endl;
std::cout << resp.DebugString() << std::endl;
} else {
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "HttpStatus=" << result.GetHttpStatus() << std::endl;
std::cout << "ErrorCode=" << result.GetErrorCode() << std::endl;
std::cout << "ErrorMsg=" << result.GetErrorMsg() << std::endl;
std::cout << "ResourceAddr=" << result.GetResourceAddr() << std::endl;
std::cout << "XCosRequestId=" << result.GetXCosRequestId() << std::endl;
std::cout << "XCosTraceId=" << result.GetXCosTraceId() << std::endl;
}
}

API Operations

For details about the API related to the object download interface, see GET Object.

Help and Support

Was this page helpful?

Help us improve! Rate your documentation experience in 5 mins.

Feedback