Search code examples
c++amazon-web-servicesamazon-s3aws-sdk-cpp

Uploading file to AWS using C++ SDK


Whenever I run my program I get the error "Unable to connect to endpoint". But I know that I can connect to that bucket because I can successfully download files that are in that bucket using the same configurations and s3Client. It gets stuck on the PutObject() line.

Here is the code.

const String KEY = "test2.txt";
const String BUCKET = "savefiles2017";


const String fileName = "test2.txt";

Client::ClientConfiguration config;
config.region = Region::US_WEST_2;
config.scheme = Http::Scheme::HTTPS;

S3Client s3Client(Auth::AWSCredentials("XXXXXX", "YYYYYY"), config); 

//putting something into s3
PutObjectRequest putObjectRequest;
putObjectRequest.WithBucket(BUCKET).WithKey(KEY);

auto requestStream = MakeShared<FStream>("PutObjectInputStream", fileName.c_str(), ios_base::in);

putObjectRequest.SetBody(requestStream);

auto putObjectOutcome = s3Client.PutObject(putObjectRequest);

if (putObjectOutcome.IsSuccess())
{
    cout << "Put object succeeded" << endl;
}
else
{
    cout << "Error while putting Object " << putObjectOutcome.GetError().GetExceptionName() <<
        " " << putObjectOutcome.GetError().GetMessage() << endl;
}

These are the includes that I am using as well

#include <string>
#include <iostream>
#include <fstream>
using namespace std;
#include <aws/core/Aws.h>
#include <aws/core/auth/AWSCredentialsProvider.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/model/PutObjectRequest.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h> 


using namespace Aws;
using namespace Aws::S3;
using namespace Aws::S3::Model;

Any help would be greatly appreciated.


Solution

  • I figured out how to fix it. I had to change the line

    auto requestStream = MakeShared<FStream>("PutObjectInputStream", fileName.c_str(), ios_base::in);
    

    To

    auto requestStream = MakeShared<FStream>("PutObjectInputStream", fileName.c_str(), ios_base::in | ios_base::binary);
    

    So I just had to add the extra flag of ios_base::binary