本文介绍如何将 OSS 文件下载到本地文件。
以下代码用于把指定的OSS文件下载到本地文件:
#include <alibabacloud/oss/OssClient.h> #include <memory> #include <fstream> using namespace AlibabaCloud::OSS; int main(void) { /*初始化OSS账号信息*/ std::string AccessKeyId = "yourAccessKeyId"; std::string AccessKeySecret = "yourAccessKeySecret"; std::string Endpoint = "yourEndpoint"; std::string BucketName = "yourBucketName"; std::string ObjectName = "yourObjectName"; /*设置下载文件的文件名*/ std::string FileNametoSave = "yourFileName"; /*初始化网络等资源*/ InitializeSdk(); ClientConfiguration conf; OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf); /*获取文件到本地文件*/ GetObjectRequest request(BucketName, ObjectName); request.setResponseStreamFactory([=]() {return std::make_shared<std::fstream>(FileNametoSave, std::ios_base::out | std::ios_base::in | std::ios_base::trunc| std::ios_base::binary); }); auto outcome = client.GetObject(request); if (outcome.isSuccess()) { std::cout << "GetObjectToFile success" << outcome.result().Metadata().ContentLength() << std::endl; } else { /*异常处理*/ std::cout << "GetObjectToFile fail" << ",code:" << outcome.error().Code() << ",message:" << outcome.error().Message() << ",requestId:" << outcome.error().RequestId() << std::endl; ShutdownSdk(); return -1; } /*释放网络等资源*/ ShutdownSdk(); return 0; }