简单上传
本文主要介绍如何从内存或从本地磁盘上传文件(Object)。
从内存中上传文件
以下代码用于从内存中上传文件:
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* 初始化OSS账号信息 */
std::string AccessKeyId = "yourAccessKeyId";
std::string AccessKeySecret = "yourAccessKeySecret";
std::string Endpoint = "yourEndpoint";
std::string BucketName = "yourBucketName";
/* yourObjectName表示上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg */
std::string ObjectName = "yourObjectName";
/* 初始化网络等资源 */
InitializeSdk();
ClientConfiguration conf;
OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
*content << "Thank you for using Alibaba Cloud Object Storage Service!";
PutObjectRequest request(BucketName, ObjectName, content);
/*(可选)请参见如下示例设置存储类型及访问权限ACL* /
//request.MetaData().addHeader("x-oss-object-acl", "private");
//request.MetaData().addHeader("x-oss-storage-class", "Standard");
/* 上传文件 */
auto outcome = client.PutObject(request);
if (!outcome.isSuccess()) {
/* 异常处理 */
std::cout << "PutObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
ShutdownSdk();
return -1;
}
/* 释放网络等资源 */
ShutdownSdk();
return 0;
}
上传本地文件
以下代码用于上传本地文件:
#include <alibabacloud/oss/OssClient.h>
#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";
/* yourObjectName表示上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg*/
std::string ObjectName = "yourObjectName";
/* 初始化网络等资源 */
InitializeSdk();
ClientConfiguration conf;
OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);
std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>("yourLocalFilename", std::ios::in | std::ios::binary);
PutObjectRequest request(BucketName, ObjectName, content);
/*(可选)请参见如下示例设置存储类型及访问权限ACL*/
//request.MetaData().addHeader("x-oss-object-acl", "private");
//request.MetaData().addHeader("x-oss-storage-class", "Standard");
auto outcome = client.PutObject(request);
if (!outcome.isSuccess()) {
/* 异常处理 */
std::cout << "PutObject fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
ShutdownSdk();
return -1;
}
/* 释放网络等资源 */
ShutdownSdk();
return 0;
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。
评论