以下使用C++将内存数据写入到S3 bucket中的Sample code, 包含鉴权认证过程
//aws sdk 相关头文件
#include "aws/core/auth/AWSCredentialsProvider.h"
#include "aws/core/client/RetryStrategy.h"
#include "aws/transfer/TransferManager.h"
#include "aws/core/Aws.h"
#include "aws/s3/S3Client.h"
int main()
{
Aws::SDKOptions options;
Aws::InitAPI(options);
string regionName = "xxx";
string accessKey = "*******";
string secret = "********";
string token = "**********************";
string bucketName = "xxx";
string objName = "s3upload/test.txt";
string content = "s3 upload test";
Aws::Client::ClientConfiguration clientConfig;
clientConfig.scheme = Aws::Http::Scheme::HTTPS;
clientConfig.connectTimeoutMs = 4 * 1000;
clientConfig.requestTimeoutMs = 4 * 1000;
clientConfig.region = regionName.c_str();
clientConfig.verifySSL = true;
Aws::Auth::AWSCredentials credentials(accessKey.c_str(), secret.c_str(), token.c_str());
auto s3Client = new Aws::sS3::S3Client(credentials, clientConfig);
const Aws::String bucket = bucketName.c_str();
const Aws::String objectName = objName.c_str();
Aws::S3::Model::PutObjectRequest request;
request.SetBucket(bucket);
request.SetKey(objectName);
const std::shared_ptr<Aws::IOStream> inputData = Aws::MakeShared<Aws::StringStream>("");
inputData->write(content.data(), content.size());
request.SetBody(inputData);
int64 startTime = ::timeGetTime();
Aws::S3::Model::PutObjectOutcome outcome = s3Client->PutObject(request);
if (!outcome.IsSuccess()) {
printf("upload to s3 error: %s", outcome.GetError().GetMessage().c_str());
return -1;
}
else
printf("upload to s3 ok: cost time: %lld ms", ::timeGetTime() - startTime);
return 0;
}
Result
upload to s3 ok: cost time: 1150 ms
注
以上上传代码基于aws-sdk-cpp v1.6, 如果升级到较新的版本,需要更新相关API
clientConfig.caFile = "xxx.crt";
Aws::Auth:s:AWSCredentials credentials(accessKey.c_str(), secret.c_str(), token.c_str());
s3Client = new Aws::S3::S3Client(credentials, nullptr, clientConfig);
Reference:
Operations on objects