C++ Upload to Amazon S3

Here’s an example of uploading a file via a POST to Amazon S3:


void TestPostAmazonS3Upload(void)
    {
    CkHttpRequest req;
    CkHttp http;

    bool success;

    //  Any string unlocks the component for the 1st 30-days.
    success = http.UnlockComponent("Anything");
    if (success != true) {
        printf("%s\n",http.lastErrorText());
        return;
    }

    req.SetFromUrl("http://something.s3.amazonaws.com/");

    req.UseUpload();
    req.AddParam("key","file1005.dat");
    req.AddParam("AWSAccessKeyId","AA6SXJPBBBBGSZHEJ6ZZ");
    req.AddParam("acl","private");
    req.AddParam("success_action_redirect","http://www.something.com/blahblah.php");
    req.AddParam("policy","abcdefhijmF0aW9uIjogIjIwMDktMTItMDFUMTI6MDA6MDAuMDAwWiIsImNvbmRpdGlvbnMiOiBbeyJidWNrZXQiOiAidHlwaG9vbmRyaXZlIn0sWyJzdGFydHMtd2l0aCIsIiRrZXkiLCIiXSx7ImFjbCI6ICJwcml2YXRlIn0seyJzdWNjZXNzX2FjdGlvbl9yZWRpcmVjdCI6ICJodHRwOi8vd3d3LnR5cGhvb250b29scy5jb20vdHlwaG9vbmRyaXZlc3RvcC5waHAifSxbInN0YXJ0cy13aXRoIiwiJENvbnRlbnQtVHlwZSIsIiJdXX0=");
    req.AddParam("signature","abcdefwFQPpsAAAuCUY2m7g/kkw=");
    req.AddParam("Content-Type","application/octet-stream");

    // The file must be added last for Amazon S3
    req.AddFileForUpload("file","payload.txt");


    //  Send the HTTP POST and get the response.  Note: This is a blocking call.
    //  The method does not return until the full HTTP response is received.
    const char * domain;
    long port;
    bool ssl;
    domain = "something.s3.amazonaws.com";
    port = 80;
    ssl = false;
    CkHttpResponse *resp = 0;
    resp = http.SynchronousRequest(domain,port,ssl,req);
    if (resp == 0 ) 
	{
        printf("%s\n",http.lastErrorText());
	}
    else 
	{
        // An HTTP response status of 303 is normal and indicates success.
        // By default, Amazon S3 will return an empty document with the status code of
        // 200 when an object is successfully uploaded.
        // 
        // Developers may choose to change this behavior by specifying a full 
        // URL within the redirect form field. If specified, on successful uploads, 
        // Amazon S3 will redirect users with a 303 to this URL...
        // (see http://doc.s3.amazonaws.com/proposals/post.html )
        printf("%s\n",http.lastErrorText());
        //  Display the HTML page returned.
        printf("%s\n",resp->bodyStr());
	delete resp;
	}
    
    }
Tags :