You can use the OSS C++ SDK V2 to copy an object within a bucket or across buckets in the same region.
Usage notes
-
Before running the example code, replace
<region>with a valid region ID, such ascn-hangzhou. -
The example code obtains access credentials from environment variables.
-
The CopyObject operation supports objects up to 1 GB. For larger objects, use multipart copy.
-
The source bucket and the destination bucket must be in the same region.
Examples
Copy an object within a bucket
The following example copies an object within the same bucket:
#include <iostream>
#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"
namespace oss = alibabacloud::oss2;
int main() {
auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
oss::OSSClient client(conf);
auto outcome = client.copyObject(
oss::models::CopyObjectRequest()
.setBucket("examplebucket")
.setKey("destobject.txt")
.setSourceBucket("examplebucket")
.setSourceKey("sourceobject.txt"));
if (!outcome.has_value()) {
auto& e = outcome.error();
std::cerr << "Failed to copy the object"
<< ", code: " << e.getCode()
<< ", message: " << e.getMessage()
<< ", requestId: " << e.getRequestId() << std::endl;
return 1;
}
auto& result = outcome.value();
std::cout << "Successfully copied the object"
<< ", status: " << result.getStatusCode()
<< ", eTag: " << result.getETag() << std::endl;
return 0;
}
Copy an object across buckets
The following example copies an object to a different bucket in the same region:
#include <iostream>
#include "alibabacloud/oss2/ClientConfiguration.h"
#include "alibabacloud/oss2/OSSClient.h"
#include "alibabacloud/oss2/credentials/CredentialsProvider.h"
namespace oss = alibabacloud::oss2;
int main() {
auto conf = oss::ClientConfiguration::loadDefault();
conf.region = "<region>";
conf.credentialsProvider = std::make_shared<oss::EnvironmentVariableCredentialsProvider>();
oss::OSSClient client(conf);
auto outcome = client.copyObject(
oss::models::CopyObjectRequest()
.setBucket("destbucket")
.setKey("destobject.txt")
.setSourceBucket("sourcebucket")
.setSourceKey("sourceobject.txt"));
if (!outcome.has_value()) {
auto& e = outcome.error();
std::cerr << "Failed to copy the object"
<< ", code: " << e.getCode()
<< ", message: " << e.getMessage()
<< ", requestId: " << e.getRequestId() << std::endl;
return 1;
}
auto& result = outcome.value();
std::cout << "Successfully copied the object across buckets"
<< ", status: " << result.getStatusCode()
<< ", eTag: " << result.getETag() << std::endl;
return 0;
}
Related documents
-
For the complete sample code, see CopyObject.cpp.
该文章对您有帮助吗?