tencent cloud

PUT Object
Last updated:2026-03-05 16:51:49
PUT Object
Last updated: 2026-03-05 16:51:49

Introduction

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

Must-Knows

If you use simple upload, you need to have write permission for the target object: when you configure the authorization policy, set action to cos:PutObject, for more authorization, see CAM-supported business APIs.
If you use the automatic multipart upload of the high-level API or implement multipart upload using the simple API, you need to have permissions for initiating multipart upload, uploading parts, and completing multipart upload for the target object: when you configure the authorization policy, set action to cos:InitiateMultipartUpload, cos:UploadPart, and cos:CompleteMultipartUpload, for more authorization, see CAM-supported business APIs.
If you use the resumable upload of the high-level API, you need to have permissions for initiating multipart upload, uploading parts, completing multipart upload, listing multipart uploads, and listing parts for the target object: when you configure the authorization policy, set action to cos:InitiateMultipartUpload, cos:UploadPart, cos:CompleteMultipartUpload, cos:ListMultipartUploads, and cos:ListParts. For more authorization, see CAM-supported business APIs.

Related Examples

Function Name
Description
Example code
high-level APIs
The high-level APIs encapsulate the multipart upload interface, enabling multi-threaded concurrent uploads of multiple parts with resumable upload capabilities. They support local file uploads only and do not support stream-based uploads.
simple APIs
PUT Object API can upload an object to a specified bucket. It does not support multi-threading or resumable upload, but supports uploading from local files and streams. It supports uploading objects up to 5GB in size. For objects larger than 5GB, please use multipart upload or high-level APIs.
Asynchronous high-level APIs
Asynchronous high-level APIs encapsulate the multipart upload interface, enabling multi-threaded concurrency for simultaneous part uploads. They support resumable uploads, progress callbacks, and upload status callback capabilities, but only support local file uploads and do not support stream-based uploads.
Asynchronous simple APIs
Asynchronous simple APIs encapsulate the simple upload interface, supporting both local file and stream-based uploads. They feature progress callbacks and upload status callback capabilities, with a maximum supported object size of 5GB. Multi-threading and resumable uploads are not supported.
Multipart Operations
Multipart upload allows splitting an entire object into multiple parts and uploading them to Cloud Object Storage (COS). This operation requires users to manually combine calls to the Initiate, Upload, and Complete APIs.

Advanced API (recommended)

Note:
Only file uploads are supported, and stream-based uploads are not supported.
High-level APIs upload multiple chunks concurrently using multithreading.
The chunk size can be configured by users and defaults to 10MB.
The upload thread pool size allows users to configure it, defaulting to 5.

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: Upload Local Files

Note:
This Demo demonstrates how to use the advanced upload API for object upload.
Only file uploads are supported, and stream-based uploads are not supported. It internally encapsulates the APIs for multipart upload.
The upload thread pool size and chunk size can be set globally. The upload thread pool is dedicated to each upload.

Method Prototype

CosResult CosAPI::MultiPutObject(const MultiPutObjectReq& req, MultiPutObjectResp* resp)

Request Example

void MultiUploadObjectDemo(qcloud_cos::CosAPI& cos) {
std::string local_file = "test_file/big_file.txt";
std::string object_name = "big_file.txt";
// This configuration is global. Once explicitly set, all subsequent upload APIs involving multi-threading will use this configuration.
CosSysConfig::SetUploadThreadPoolSize(5); // Upload thread pool size, defaulting to 5
CosSysConfig::SetUploadPartSize(10 * 1024 * 1024); // Upload part size, default 10M

qcloud_cos::MultiPutObjectReq req(bucket_name, object_name, local_file);
qcloud_cos::MultiPutObjectResp resp;
qcloud_cos::CosResult result = cos.MultiPutObject(req, &resp);

std::cout << "===================MultiUploadObject=======================" << std::endl;
if (result.IsSucc()) {
std::cout << "MultiUpload Succ." << std::endl;
std::cout << resp.GetLocation() << std::endl;
std::cout << resp.GetKey() << std::endl;
std::cout << resp.GetBucket() << std::endl;
std::cout << resp.GetEtag() << std::endl;
} else {
std::cout << "MultiUpload Fail." << std::endl;
// Get the specific step where the failure occurred
std::string resp_tag = resp.GetRespTag();
if ("Init" == resp_tag) {
// print result
} else if ("Upload" == resp_tag) {
// print result
} else if ("Complete" == resp_tag) {
// print result
}
PrintResult(result, resp);
}
std::cout << "===========================================================" << std::endl;
}

Parameter Description

Parameter Name
Description
Type
req
Upload file request
MultiPutObjectReq
resp
Upload file response
MultiPutObjectResp
MultiPutObjectReq 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
SetXCosStorageClass
Set the storage class: req.SetXCosStorageClass("xxxx").
string
MultiPutObjectResp Member Function Description:
Member functions
Description
Return Type
GetRespTag
Obtain the failure stage: Init/Upload/Complete
string
GetXCosServerSideEncryption
Obtain the server-side encryption algorithm used
string
GetEtag
Obtain the Etag of the stored object.
string
GetXCosRequestId
Obtain the request ID.

The CosSysConfig class is used for related configurations. In this sample, the main member functions are as follows:
Member functions
Description
Parameter Type
SetUploadPartSize
Set the part size for multipart upload, unit: byte (Byte), default: 10MB.
The setting method is CosSysConfig::SetUploadPartSize(10 * 1024 * 1024).
uint64_t
SetUploadThreadPoolSize
Set the upload thread pool size, default: 5.
The setting method is CosSysConfig::SetUploadThreadPoolSize(5).
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;
}
}

Simple APIs

Preliminary Preparation: Create CosAPI

Before the COS API is called, 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: Upload Local Files

Note:
This Demo demonstrates how to use the COS C++ SDK to perform simple uploads of local files.
Supports uploading objects up to 5GB in size.

Method Prototype

CosAPI::PutObject(const PutObjectByFileReq& req, PutObjectByFileResp* resp)

Request Example

void PutObjectByFileDemo(qcloud_cos::CosAPI& cos) {
std::string object_name = "test.txt";
std::string file_path = "./test_file/text.txt";
qcloud_cos::PutObjectByFileReq req(bucket_name, object_name, file_path);
// Upload 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::PutObjectByFileResp resp;
qcloud_cos::CosResult result = cos.PutObject(req, &resp);
std::cout << "====================PutObjectByFile======================" << std::endl;
PrintResult(result, resp);
std::cout << "=========================================================" << std::endl;
}

Parameter Description

Parameter Name
Description
Type
req
Upload file request
PutObjectByFileReq
resp
Upload file response
PutObjectByFileResp
PutObjectByFileReq 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
SetXCosStorageClass
Set the storage class: req.SetXCosStorageClass("xxxx").
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
PutObjectByFileResp Member Function Description:
Member functions
Description
Return Type
GetVersionId
Get the version number of the Object. If versioning is not enabled for the Bucket, an empty string is returned.
string
GetXCosServerSideEncryption
Obtain the server-side encryption algorithm used
string
GetEtag
Obtain the Etag of the stored 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: Upload Stream Type

Note:
This Demo demonstrates how to perform simple stream-type uploads using the COS C++ SDK.
Supports uploading objects up to 5GB in size.

Method Prototype

CosResult CosAPI::PutObject(const PutObjectByStreamReq& req, PutObjectByStreamResp* resp)

Request Example

void PutObjectByStreamDemo(qcloud_cos::CosAPI& cos) {
std::istringstream iss("put object");
std::string object_name = "text.txt";
qcloud_cos::PutObjectByStreamReq req(bucket_name, object_name, iss);
// Upload 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::PutObjectByStreamResp resp;
qcloud_cos::CosResult result = cos.PutObject(req, &resp);
std::cout << "===================PutObjectByStream=====================" << std::endl;
PrintResult(result, resp);
std::cout << "=========================================================" << std::endl;
}

Parameter Description

Parameter Name
Description
Type
req
Upload file request
PutObjectByStreamReq
resp
Upload file response
PutObjectByStreamResp
PutObjectByStreamReq 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
in_stream
Input stream, which can be set via the constructor.
istream
SetXCosStorageClass
Set the storage class: req.SetXCosStorageClass("xxxx").
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
PutObjectByStreamResp Member Function Description:
Member functions
Description
Return Type
GetVersionId
Get the version number of the Object. If versioning is not enabled for the Bucket, an empty string is returned.
string
GetXCosServerSideEncryption
Obtain the server-side encryption algorithm used
string
GetEtag
Obtain the Etag of the stored 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:
Only file uploads are supported, and stream-based uploads are not supported.
Upload multiple chunks concurrently using multithreading.
The chunk size can be configured by users and defaults to 10MB.
The upload thread pool size allows users to configure it, defaulting to 5.
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: Upload Local Files

Note:
This Demo demonstrates how to use the asynchronous advanced upload API for object upload, including examples of progress callbacks and upload status callbacks.
Only file uploads are supported, and stream-based uploads are not supported. It internally encapsulates the APIs for multipart upload.
The upload thread pool size and chunk size can be set globally. The upload thread pool is dedicated to each upload.
The asynchronous thread pool size can be set globally. This thread pool is globally shared and used for asynchronous scheduling.
Method Prototype
SharedAsyncContext CosAPI::AsyncMultiPutObject(const AsyncMultiPutObjectReq& req)
Request Example
/*
* This method is an example of a progress callback for asynchronous object upload
*/
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 upload
*/
void PutObjectAsyncDoneCallback(const SharedAsyncContext& context, void* user_data) {
UNUSED_PARAM(user_data)
std::cout << "PutObjectAsyncDoneCallback, BucketName:" << context->GetBucketName() << ", ObjectName:" << context->GetObjectName() << ", LocalFile:" << context->GetLocalFilePath() << std::endl;
if (context->GetResult().IsSucc()) {
// Obtain the response
std::cout << "AsyncMultiPutObject succeed" << std::endl;
std::cout << "Result:" << context->GetResult().DebugString() << std::endl;
AsyncResp resp = context->GetAsyncResp();
// std::cout << "Location:" << resp.GetLocation() << std::endl;
// std::cout << "Bucket:" << resp.GetBucket() << std::endl;
// std::cout << "Key:" << resp.GetKey() << std::endl;
std::cout << "ETag:" << resp.GetEtag() << std::endl;
std::cout << "Crc64:" << resp.GetXCosHashCrc64Ecma() << std::endl;
} else {
std::cout << "AsyncMultiPutObject failed" << std::endl;
std::cout << "ErrorMsg:" << context->GetResult().GetErrorMsg() << std::endl;
}
}

void AsyncMultiPutObjectDemo(qcloud_cos::CosAPI& cos) {
// This configuration is global. Once explicitly set, all subsequent asynchronous APIs will use this configuration.
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::AsyncMultiPutObjectReq req(bucket_name, object_name, local_file);
req.SetRecvTimeoutInms(1000 * 60);
// Set the upload progress callback
req.SetTransferProgressCallback(&ProgressCallback);
// Set the upload status callback
req.SetDoneCallback(&PutObjectAsyncDoneCallback);
// Set private data, which corresponds to user_data in the callback
req.SetUserData(&req);

// Start upload
SharedAsyncContext context = cos.AsyncMultiPutObject(req);

std::cout << "===================AsyncMultiPutObject======================" << std::endl;
// Wait for the upload to complete
std::cout << "wait finish..." << std::endl;
context->WaitUntilFinish();

// Check the result
if (context->GetResult().IsSucc()) {
// Obtain the response
std::cout << "AsyncMultiPutObject succeed" << std::endl;
std::cout << "Result:" << context->GetResult().DebugString() << std::endl;
AsyncResp resp = context->GetAsyncResp();
// std::cout << "Location:" << resp.GetLocation() << std::endl;
// std::cout << "Bucket:" << resp.GetBucket() << std::endl;
// std::cout << "Key:" << resp.GetKey() << std::endl;
std::cout << "ETag:" << resp.GetEtag() << std::endl;
std::cout << "Crc64:" << resp.GetXCosHashCrc64Ecma() << std::endl;
} else {
std::cout << "AsyncMultiPutObject failed" << std::endl;
std::cout << "ErrorMsg:" << context->GetResult().GetErrorMsg() << std::endl;
}
std::cout << "============================================================" << std::endl;
}
Parameter Descriptions
Parameter Name
Description
Type
req
Upload file request
AsyncMultiPutObjectReq
Description of AsyncMultiPutObjectReq members or functions:
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
SetXCosStorageClass
Set the storage class: req.SetXCosStorageClass("xxxx").
string
SetRecvTimeoutInms
Set the receive timeout in milliseconds (ms). Default: 5s.
uint64_t
SetTransferProgressCallback
Set the upload progress callback method
TransferProgressCallback
SetDoneCallback
Set the upload 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 upload 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 upload object.
string
GetEtag
Obtain the Etag of the stored 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
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 the COS API is called, 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: Upload Local Files

Note:
This Demo demonstrates how to use the COS C++ SDK for asynchronous simple uploads of local files.
Supports uploading objects up to 5GB in size.
This sample includes progress callback and upload status callback.
Method Prototype
SharedAsyncContext CosAPI::AsyncPutObject(const AsyncPutObjectReq& req)
Request Example
/*
* This method is an example of a progress callback for asynchronous object upload
*/
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 upload
*/
void PutObjectAsyncDoneCallback(const SharedAsyncContext& context, void* user_data) {
UNUSED_PARAM(user_data)
std::cout << "PutObjectAsyncDoneCallback, BucketName:" << context->GetBucketName() << ", ObjectName:" << context->GetObjectName() << ", LocalFile:" << context->GetLocalFilePath() << std::endl;
if (context->GetResult().IsSucc()) {
// Obtain the response
std::cout << "PutObject succeed" << std::endl;
std::cout << "Result:" << context->GetResult().DebugString() << std::endl;
AsyncResp resp = context->GetAsyncResp();
// std::cout << "Location:" << resp.GetLocation() << std::endl;
// std::cout << "Bucket:" << resp.GetBucket() << std::endl;
// std::cout << "Key:" << resp.GetKey() << std::endl;
std::cout << "ETag:" << resp.GetEtag() << std::endl;
std::cout << "Crc64:" << resp.GetXCosHashCrc64Ecma() << std::endl;
} else {
std::cout << "PutObject failed" << std::endl;
std::cout << "ErrorMsg:" << context->GetResult().GetErrorMsg() << std::endl;
}
}

void AsyncPutObjectDemo(qcloud_cos::CosAPI& cos) {
std::string local_file = "test_file/text.txt";
std::string object_name = "text.txt";
qcloud_cos::AsyncPutObjectReq req(bucket_name, object_name, local_file);
req.SetRecvTimeoutInms(1000 * 60);
// Set the upload progress callback
req.SetTransferProgressCallback(&ProgressCallback);
// Set the upload status callback
req.SetDoneCallback(&PutObjectAsyncDoneCallback);
// Set private data, which corresponds to user_data in the callback
req.SetUserData(&req);

// Start upload
SharedAsyncContext context = cos.AsyncPutObject(req);
std::cout << "===================AsyncPutObjectByFile======================" << std::endl;
// Wait for the upload to complete
std::cout << "wait finish..." << std::endl;
context->WaitUntilFinish();
// Check the result
if (context->GetResult().IsSucc()) {
// Obtain the response
std::cout << "AsyncPutObjectByFile succeed" << std::endl;
std::cout << "Result:" << context->GetResult().DebugString() << std::endl;
AsyncResp resp = context->GetAsyncResp();
// std::cout << "Location:" << resp.GetLocation() << std::endl;
// std::cout << "Bucket:" << resp.GetBucket() << std::endl;
// std::cout << "Key:" << resp.GetKey() << std::endl;
std::cout << "ETag:" << resp.GetEtag() << std::endl;
std::cout << "Crc64:" << resp.GetXCosHashCrc64Ecma() << std::endl;
} else {
std::cout << "AsyncPutObjectByFile failed" << std::endl;
std::cout << "ErrorMsg:" << context->GetResult().GetErrorMsg() << std::endl;
}
std::cout << "=============================================================" << std::endl;
}
Parameter Descriptions
Parameter Name
Description
Type
req
Upload file request
AsyncPutObjectReq
Description of AsyncPutObjectReq Members or Functions:
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
SetXCosStorageClass
Set the storage class: req.SetXCosStorageClass("xxxx").
string
SetRecvTimeoutInms
Set the receive timeout in milliseconds (ms). Default: 5s.
uint64_t
SetTransferProgressCallback
Set the upload progress callback method
TransferProgressCallback
SetDoneCallback
Set the upload 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 upload 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 upload object.
string
GetEtag
Obtain the Etag of the stored 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;
}
}

Use Case: Upload Stream Type

Note:
This Demo demonstrates how to perform simple stream-type uploads using the COS C++ SDK.
Supports uploading objects up to 5GB in size.
Method Prototype
SharedAsyncContext CosAPI::AsyncPutObject(const AsyncPutObjectByStreamReq& req)
Request Example
/*
* This method is an example of a progress callback for asynchronous object upload
*/
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 upload
*/
void PutObjectAsyncDoneCallback(const SharedAsyncContext& context, void* user_data) {
UNUSED_PARAM(user_data)
std::cout << "PutObjectAsyncDoneCallback, BucketName:" << context->GetBucketName() << ", ObjectName:" << context->GetObjectName() << ", LocalFile:" << context->GetLocalFilePath() << std::endl;
if (context->GetResult().IsSucc()) {
// Obtain the response
std::cout << "AsyncMultiPutObject succeed" << std::endl;
std::cout << "Result:" << context->GetResult().DebugString() << std::endl;
AsyncResp resp = context->GetAsyncResp();
// std::cout << "Location:" << resp.GetLocation() << std::endl;
// std::cout << "Bucket:" << resp.GetBucket() << std::endl;
// std::cout << "Key:" << resp.GetKey() << std::endl;
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;
}
}

void AsyncPutObjectDemo(qcloud_cos::CosAPI& cos) {
std::string object_name = "text.txt";
std::istringstream iss("put object");
qcloud_cos::AsyncPutObjectByStreamReq req(bucket_name, object_name, iss);
req.SetRecvTimeoutInms(1000 * 60);
// Set the upload progress callback
req.SetTransferProgressCallback(&ProgressCallback);
// Set the upload status callback
req.SetDoneCallback(&PutObjectAsyncDoneCallback);
// Set private data, which corresponds to user_data in the callback
req.SetUserData(&req);
// Start upload
SharedAsyncContext context = cos.AsyncPutObject(req);
std::cout << "===================AsyncPutObjectByStream======================" << std::endl;
// Wait for the upload to complete
std::cout << "wait finish..." << std::endl;
context->WaitUntilFinish();
// Check the result
if (context->GetResult().IsSucc()) {
// Obtain the response
std::cout << "AsyncPutObjectByStream succeed" << std::endl;
std::cout << "Result:" << context->GetResult().DebugString() << std::endl;
AsyncResp resp = context->GetAsyncResp();
// std::cout << "Location:" << resp.GetLocation() << std::endl;
// std::cout << "Bucket:" << resp.GetBucket() << std::endl;
// std::cout << "Key:" << resp.GetKey() << std::endl;
std::cout << "ETag:" << resp.GetEtag() << std::endl;
std::cout << "Crc64:" << resp.GetXCosHashCrc64Ecma() << std::endl;
} else {
std::cout << "AsyncPutObjectByStream failed" << std::endl;
std::cout << "ErrorMsg:" << context->GetResult().GetErrorMsg() << std::endl;
}
std::cout << "===============================================================" << std::endl;
}
Parameter Descriptions
Parameter Name
Description
Type
req
Upload file request
AsyncPutObjectByStreamReq
AsyncPutObjectByStreamReq 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
in_stream
Input stream, which can be set via the constructor.
istream
SetXCosStorageClass
Set the storage class: req.SetXCosStorageClass("xxxx").
string
SetRecvTimeoutInms
Set the receive timeout in milliseconds (ms). Default: 5s.
uint64_t
SetTransferProgressCallback
Set the upload progress callback method.
TransferProgressCallback
SetDoneCallback
Set the upload 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 upload 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 upload object.
string
GetEtag
Obtain the Etag of the stored 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;
}
}

Multipart Operations

Multipart operations involve using a series of chunks during large file uploads to mitigate various interruption issues caused by prolonged upload times. For more details on multipart uploads, see Multipart Upload. The process flow for uploading objects using multipart upload is as follows.
Note:
If the file to be uploaded can be fully obtained, it is recommended to use the advanced 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;
}

Operation Process

Multipart Upload Process

1. Initiate multipart upload (Initiate Multipart Upload) to obtain the UploadId.
2. Use the UploadId to upload parts (Upload Part).
3. Complete multipart upload (Complete Multipart Upload).

Resuming the Multipart Upload Process

1. If the UploadId is not recorded, you need to first list multipart uploads (List Multipart Uploads) to obtain the UploadId for the corresponding file.
2. Use the UploadId to list uploaded parts (List Parts).
3. Use the UploadId to upload the remaining parts (Upload Part).
4. Complete multipart upload (Complete Multipart Upload).

Terminate Multipart Upload Process

1. If the UploadId is not recorded, list multipart uploads (List Multipart Uploads) to obtain the UploadId for the corresponding file.
2. Abort multipart upload and delete uploaded parts (Abort Multipart Upload).

Use Case: Initiate Multipart Upload

Initiate multipart upload operation to obtain the corresponding uploadId for subsequent operations.
Method Prototype
CosResult CosAPI::InitMultiUpload(const InitMultiUploadReq& req, InitMultiUploadResp* resp)
Request Example
void InitMultiUpload(qcloud_cos::CosAPI& cos, const std::string& bucket_name,
const std::string& object_name, std::string* upload_id) {
qcloud_cos::InitMultiUploadReq req(bucket_name, object_name);
qcloud_cos::InitMultiUploadResp resp;
qcloud_cos::CosResult result = cos.InitMultiUpload(req, &resp);
std::cout << "=====================InitMultiUpload====================="<< std::endl;
PrintResult(result, resp);
std::cout << "========================================================="<< std::endl;

*upload_id = resp.GetUploadId();
}
Parameter Descriptions
Parameter Name
Description
Type
req
Initiate multipart upload request
InitMultiUploadReq
resp
Initiate multipart upload response
InitMultiUploadResp
InitMultiUploadReq member description:
Member
Setting Method
Description
Type
bucket_name
Constructor or set method
The naming format for buckets is BucketName-APPID. For details, see Naming Conventions
string
object_name
Constructor or set method
An object key is a unique identifier for an object in a 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
InitMultiUploadResp member function description:
Member functions
Description
Type
GetUploadId
Get UploadId
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: Query Multipart Upload Tasks

List multipart uploads (List Multipart Uploads) to obtain all ongoing upload tasks, from which the required uploadId can be obtained.
Method Prototype
CosResult ListMultipartUpload(const ListMultipartUploadReq& req, ListMultipartUploadResp* resp)
Request Example
void ListMultipartUpload(qcloud_cos::CosAPI& cos,
const std::string& bucket_name) {
qcloud_cos::ListMultipartUploadReq req(bucket_name);
qcloud_cos::ListMultipartUploadResp resp;
qcloud_cos::CosResult result = cos.ListMultipartUpload(req, &resp);
std::vector<Upload> rst = resp.GetUpload();

for (std::vector<qcloud_cos::Upload>::const_iterator itr = rst.begin(); itr != rst.end(); ++itr) {
const qcloud_cos::Upload& upload = *itr;
std::cout << "key = " << upload.m_key << ", uploadid= " << upload.m_uploadid
<< ", storagen class = " << upload.m_storage_class
<< ", m_initiated= " << upload.m_initiated << std::endl;
}

std::cout << "===================ListMultipartUpload=====================" << std::endl;
PrintResult(result, resp);
std::cout << "===========================================================" << std::endl;
}
Parameter Descriptions
Parameter Name
Description
Type
req
List Multipart Uploads Request
ListMultipartUploadReq
resp
List Multipart Uploads Response
ListMultipartUploadResp
ListMultipartUploadReq Members and Functions:
Member or Function
Description
Parameter Type
bucket_name
The bucket name can be configured via the constructor or set method.
The naming format for buckets is BucketName-APPID. For details, see Naming Conventions
string
SetKeyMarker
List entries starting from this key value
Set via req.SetKeyMarker("xxx").
string
SetDelimiter
The delimiter is a symbol. If the Prefix is specified, the identical paths between the Prefix and the delimiter are grouped into a category and defined as a Common Prefix, and all Common Prefixes are listed. If the Prefix is not specified, identical paths from the beginning to the delimiter are grouped and defined as a Common Prefix.
Set via req.SetDelimiter("xxx").
string
SetPrefix
The returned Object key must be prefixed with Prefix. Note that when using prefix query, the returned key will still contain the Prefix
Set via req.SetPrefix("xxx").
string
SetUploadIdMarker
The listing starts from this UploadId value.
Set via req.SetUploadIdMarker("xxx").
string
SetMaxUploads
Set the maximum number of multiparts returned. The legal value is 1 to 1000
Set via req.SetMaxUploads("xxx").
string
SetEncodingType
Specifies the encoding type of the return value. Valid value: url.
Set via req.SetEncodingType("xxx").
string
ListMultipartUploadResp Member Functions:
Member functions
Description
Type
GetUpload
Obtain the UploadId list. Refer to the sample for usage.
vector<qcloud_cos::Upload>
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
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 Cases: Uploading Parts

Method Prototype
CosResult CosAPI::UploadPartData(const UploadPartDataReq& req, UploadPartDataResp* resp)
Request Example
void UploadPartData(qcloud_cos::CosAPI& cos, const std::string& bucket_name,
const std::string& object_name,
const std::string& upload_id, std::fstream& is,
uint64_t number, std::string* etag) {
qcloud_cos::UploadPartDataReq req(bucket_name, object_name, upload_id, is);
req.SetPartNumber(number);
qcloud_cos::UploadPartDataResp resp;
qcloud_cos::CosResult result = cos.UploadPartData(req, &resp);
*etag = resp.GetEtag();

std::cout << "======================UploadPartData====================="<< std::endl;
PrintResult(result, resp);
std::cout << "========================================================="<< std::endl;
}
Parameter Descriptions
Parameter Name
Description
Type
req
Upload file request
UploadPartDataReq
resp
Upload file response
UploadPartDataResp
UploadPartDataReq Members and Functions:
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
in_stream
Input stream, which can be set via the constructor.
istream
upload_id
upload_id, which can be set via the constructor.

SetXCosStorageClass
Set the storage class: req.SetXCosStorageClass("xxxx").
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
UploadPartDataResp Member Functions:
Member functions
Description
Return Type
GetEtag
Obtain the Etag of the stored 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: Query the Uploaded Parts

Query the uploaded mulitparts in a specific multiple parts uploading (List Parts).
Method Prototype
CosResult ListParts(const ListPartsReq& req, ListPartsResp* resp)
Request Example
void ListParts(qcloud_cos::CosAPI& cos, const std::string& bucket_name,
const std::string& object_name, const std::string& upload_id) {
qcloud_cos::ListPartsReq req(bucket_name, object_name, upload_id);
req.SetMaxParts(100);
req.SetPartNumberMarker("1");
qcloud_cos::ListPartsResp resp;
qcloud_cos::CosResult result = cos.ListParts(req, &resp);
std::cout << "===================ListParts=====================" << std::endl;
PrintResult(result, resp);
std::cout << "=================================================" << std::endl;
}
Parameter Descriptions
Parameter Name
Description
Type
req
Query the specified multipart upload task request.
ListPartsReq
resp
List Multipart Uploads Response
ListPartsResp
ListPartsReq Members and Functions:
Member or Function
Description
Parameter Type
bucket_name
The bucket name can be configured via the constructor or set method.
The naming format for buckets is BucketName-APPID. For details, see Naming Conventions
string
object_name
The path for multipart uploads to COS, that is, the object key. For example, the object key is folder/picture.jpg
string
upload_id
Identifies the uploadId of the specified multi-part upload
string
SetMaxParts
Maximum number of entries returned in a single response. The default value is 1,000.
string
SetPartNumberMarker
By default, entries are listed in UTF-8 binary order, starting from the marker.
string
ListPartsResp Members and Functions:
Member functions
Description
Return Type
GetParts
Obtain the list of Parts, including the ETag and number of each part.
vector<Part>
GetNextPartNumberMarker
Next list starting marker
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: Complete Multipart Upload

Complete multipart upload of the entire file.
Note:
After the multipart upload is completed, the multipart upload task will be deleted, and the uploadId corresponding to the task will no longer be valid.
Method Prototype
CosResult CompleteMultiUpload(const CompleteMultiUploadReq& req, CompleteMultiUploadResp* resp)
Request Example
void CompleteMultiUpload(qcloud_cos::CosAPI& cos,
const std::string& bucket_name,
const std::string& object_name,
const std::string& upload_id,
const std::vector<std::string>& etags,
const std::vector<uint64_t>& numbers) {
qcloud_cos::CompleteMultiUploadReq req(bucket_name, object_name, upload_id);
qcloud_cos::CompleteMultiUploadResp resp;
req.AddParam("versionId", "MTg0NDY3NDI1NjQ4NjUyMjQ1MTA");
req.SetEtags(etags);
req.SetPartNumbers(numbers);
qcloud_cos::CosResult result = cos.CompleteMultiUpload(req, &resp);

std::cout << "===================Complete=============================" << std::endl;
PrintResult(result, resp);
std::cout << "========================================================" << std::endl;
}
Parameter Descriptions
Parameter Name
Description
Type
req
Complete multipart upload request
CompleteMultiUploadReq
resp
Complete multipart upload response
CompleteMultiUploadResp
CompleteMultiUploadReq member and function description:
Members and Functions
Description
Type
bucket_name
The naming format for buckets is BucketName-APPID. For details, see Naming Conventions
string
object_name
Specifies the path for the multipart upload to COS, that is, the Object Key. For example, the object key is folder/picture.jpg
string
upload_id
Identifies the uploadId of the specified multi-part upload
string
SetEtags
Identifies the Etag returned by the multipart upload, which must correspond sequentially to the numbers.
req.SetEtags(etags)
vector<std::string>
SetPartNumbers
Represents the part number, which must correspond sequentially to the etags.
req.SetPartNumbers(numbers)
vector<uint64_t>
CompleteMultiUploadResp member function description:
Member functions
Description
Return Type
GetVersionId
Get the version number of the Object. If versioning is not enabled for the Bucket, an empty string is returned.
string
GetXCosServerSideEncryption
Obtain the server-side encryption algorithm used
string
GetEtag
Obtain the Etag of the stored 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: Terminate Multipart Upload

Abort a multipart upload operation and delete uploaded parts (Abort Multipart Upload).
Note:
After a multipart upload is aborted, both the multipart upload task and the uploaded parts will be deleted; the corresponding uploadId becomes invalid.
Method Prototype
CosResult AbortMultiUpload(const AbortMultiUploadReq& req, AbortMultiUploadResp* resp)
Request Example
void AbortMultiUpload(qcloud_cos::CosAPI& cos, const std::string& bucket_name,
const std::string& object_name,
const std::string& upload_id) {
qcloud_cos::AbortMultiUploadReq req(bucket_name, object_name, upload_id);
qcloud_cos::AbortMultiUploadResp resp;
qcloud_cos::CosResult result = cos.AbortMultiUpload(req, &resp);
std::cout << "======================AbortUploadPart=====================";
PrintResult(result, resp);
std::cout << "=========================================================";
}
Parameter Descriptions
Parameter Name
Description
Type
req
Abort multipart upload request
AbortMultiUploadReq
resp
Abort Multipart Upload Response
AbortMultiUploadResp
AbortMultiUploadReq member and function description:
Members and Functions
Description
Type
bucket_name
The naming format for buckets is BucketName-APPID. For details, see Naming Conventions
string
object_name
Specifies the path for the multipart upload to COS, that is, the Object Key. For example, the object key is folder/picture.jpg
string
upload_id
Identifies the uploadId of the specified multi-part upload
string
AbortMultiUploadResp member function description:
Member functions
Description
Return Type
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: Complete Sample of Multipart Upload

Note:
This Demo demonstrates how to combine and use chunked operations for object upload.
Only stream-based uploads are supported.
void PutPartDemo(qcloud_cos::CosAPI& cos) {
std::string object_name = "big_file.txt";

// 1. InitMultiUpload
qcloud_cos::InitMultiUploadReq init_req(bucket_name, object_name);
qcloud_cos::InitMultiUploadResp init_resp;
qcloud_cos::CosResult init_result = cos.InitMultiUpload(init_req, &init_resp);
std::cout << "=====================InitMultiUpload=====================" << std::endl;
PrintResult(init_result, init_resp);
std::cout << "=========================================================" << std::endl;

// 2. UploadPartData
// For the UploadPartData section, the part count and part size can be selected based on actual needs. Here, taking 2 parts as an example
std::vector<std::string> etags;
std::vector<uint64_t> part_numbers;
std::string upload_id = init_resp.GetUploadId();
{
uint64_t part_number = 1;
// Simulate uploading chunked data; here, using 1M as an example
std::vector<char> data(1024 * 1024, 'A');
std::string content(data.begin(), data.end());
std::istringstream iss(content);
qcloud_cos::UploadPartDataReq req(bucket_name, object_name, upload_id, iss);
req.SetPartNumber(part_number);
qcloud_cos::UploadPartDataResp resp;
qcloud_cos::CosResult result = cos.UploadPartData(req, &resp);
std::cout << "==================UploadPartDataResp1=====================" << std::endl;
PrintResult(result, resp);
std::cout << "==========================================================" << std::endl;
if (result.IsSucc()) {
part_numbers.push_back(part_number);
etags.push_back(resp.GetEtag());
}
}
{
uint64_t part_number = 2;
std::istringstream iss("The last part can be smaller than 1MB");
qcloud_cos::UploadPartDataReq req(bucket_name, object_name, upload_id, iss);
req.SetPartNumber(part_number);
qcloud_cos::UploadPartDataResp resp;
qcloud_cos::CosResult result = cos.UploadPartData(req, &resp);
std::cout << "==================UploadPartDataResp2=====================" << std::endl;
PrintResult(result, resp);
std::cout << "==========================================================" << std::endl;
if (result.IsSucc()) {
part_numbers.push_back(part_number);
etags.push_back(resp.GetEtag());
}
}
// 3. Complete
CompleteMultiUploadReq comp_req(bucket_name, object_name, upload_id);
CompleteMultiUploadResp comp_resp;

comp_req.SetEtags(etags);
comp_req.SetPartNumbers(part_numbers);

qcloud_cos::CosResult result = cos.CompleteMultiUpload(comp_req, &comp_resp);

std::cout << "===================Complete=============================" << std::endl;
PrintResult(result, comp_resp);
std::cout << "========================================================" << std::endl;
return;
}

API Operations

For API documentation on simple operations, see the PUT Object document.
For API documentation on multipart operations, see the List Multipart Uploads, Initiate Multipart Upload, Upload Part, List Parts, Abort Multipart Upload, and Complete Multipart Upload documents.

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

Feedback