Sample code for 30+ languages & platforms
Java Requires Chilkat v11.6.0+

Amazon S3: Upload Binary Data from BinData

See more S3 - REST Examples

Upload one object with PutObject. Requires s3:PutObject; KMS-encrypted objects can need additional KMS permissions. An existing key is overwritten in an unversioned bucket or gets a new version when versioning is enabled. Successful PUT normally has an empty body. Do not label uncompressed data with Content-Encoding: gzip.

BinData holds the whole input in memory; use the streaming example for large files. The configured region determines both the TLS hostname and signing scope.

For general purpose S3 buckets, using regional HTTPS endpoints and AWS Signature Version 4. Directory buckets (S3 Express), access points, Outposts, and other AWS partitions need their own endpoint/authentication rules. Use a bucket name without dots for these virtual-hosted TLS examples; see the path-style example for dotted names.

Provide current IAM credentials in a private qa_data/aws/s3.json file with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This file is explicitly loaded; these examples do not discover profiles or refresh credentials. Keep it outside public content and source control. The session token is included in the signed request. TLS certificate verification is enabled on the Socket used by Rest.

Transport success and HTTP success are different. Keep full diagnostics private; signed requests and presigned URLs can contain credentials or grant access. For retryable reads use bounded backoff with jitter. Before retrying a write with an uncertain outcome, check the resource state. Keep keys, upload IDs, version IDs, ETags, and large sizes as strings.

AWS PutObject reference

Chilkat Java Downloads

Java
import com.chilkatsoft.chilkat2.AuthAws;
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Rest;
import com.chilkatsoft.chilkat2.Socket;
import com.chilkatsoft.chilkat2.StringBuilder;
import com.chilkatsoft.chilkat2.Xml;

public class ChilkatExample {

    public static void main(String[] args) {
        boolean success = false;

        // StringBuilder compares text by value in every generated language.
        StringBuilder textCompare = new StringBuilder();
        // Assumes Chilkat is unlocked. See Global Unlock Sample.
        success = false;
        // Private configuration, not a file in public web content or source control.
        // Load current IAM credentials authorized for the S3 operation.
        JsonObject credentials = new JsonObject();
        credentials.setStrict(true);
        try {
            credentials.loadFile("qa_data/aws/s3.json");
        } catch (ChilkatException e) {
            System.out.println("Could not load private AWS credentials.");
            return;
        }

        textCompare.clear();
        textCompare.setString(credentials.stringOf("access_key"));
        boolean sameText1 = textCompare.contentsEqual("", true);
        if ((credentials.jsonTypeOf("access_key") != 1) || (sameText1)) {
            System.out.println("Missing or invalid access_key.");
            return;
        }

        textCompare.clear();
        textCompare.setString(credentials.stringOf("secret_key"));
        boolean sameText2 = textCompare.contentsEqual("", true);
        if ((credentials.jsonTypeOf("secret_key") != 1) || (sameText2)) {
            System.out.println("Missing or invalid secret_key.");
            return;
        }

        // General purpose bucket in the commercial AWS partition.
        String region = "us-west-2";
        String bucketName = "amzn-s3-demo-bucket";
        StringBuilder endpoint = new StringBuilder();
        try {
            endpoint.append(bucketName);

            endpoint.append(".");

            endpoint.append("s3.");

            endpoint.append(region);

            endpoint.append(".amazonaws.com");
        } catch (ChilkatException e) {
            System.out.println("Could not build text.");
            return;
        }

        AuthAws aws = new AuthAws();
        aws.setAccessKey(credentials.stringOf("access_key"));
        aws.setSecretKey(credentials.stringOf("secret_key"));
        aws.setRegion(region);
        aws.setServiceName("s3");
        aws.setSignatureVersion(4);
        Rest rest = new Rest();
        rest.setConnectTimeoutMs(20000);
        rest.setIdleTimeoutMs(60000);
        try {
            rest.setAuthAws(aws);
        } catch (ChilkatException e) {
            System.out.println("Could not configure AWS signing.");
            return;
        }

        // Temporary credentials require this token in every signed query.
        // Keep request URLs private. Do not clear this parameter between requests.
        if (credentials.hasMember("session_token")) {
            if (credentials.jsonTypeOf("session_token") != 1) {
                System.out.println("session_token must be a string.");
                return;
            }

            textCompare.clear();
            textCompare.setString(credentials.stringOf("session_token"));
            boolean sameText3 = textCompare.contentsEqual("", true);
            if (!sameText3) {
                try {
                    rest.addQueryParam("X-Amz-Security-Token", credentials.stringOf("session_token"));
                } catch (ChilkatException e) {
                    System.out.println("Could not prepare the request.");
                    return;
                }
            }
        }

        // Connect to the SAME hostname used for TLS verification and request signing.
        Socket connection = new Socket();
        connection.setRequireSslCertVerify(true);
        connection.setMaxReadIdleMs(60000);
        connection.setMaxSendIdleMs(60000);
        try {
            connection.connect(endpoint.getAsString(), 443, true, 20000);
        } catch (ChilkatException e) {
            System.out.println("TLS connection failed; inspect diagnostics privately.");
            return;
        }

        try {
            rest.useConnection(connection, true);
        } catch (ChilkatException e) {
            System.out.println("Could not attach the TLS connection.");
            return;
        }

        Xml xml = new Xml();
        xml.setStrict(true);
        // Supply an unencoded object key, not a URL. Preserve slashes in the key.
        String objectKey = "documents/example.txt";
        StringBuilder objectPath = new StringBuilder();
        try {
            objectPath.append(objectKey);
        } catch (ChilkatException e) {
            System.out.println("Could not build text.");
            return;
        }

        try {
            objectPath.encode("url_rfc3986", "utf-8");
        } catch (ChilkatException e) {
            System.out.println("Could not encode the object key.");
            return;
        }

        int restoredSlashes = objectPath.replace("%2F", "/");
        try {
            objectPath.prepend("/");

            rest.addHeader("Content-Type", "application/octet-stream");
        } catch (ChilkatException e) {
            System.out.println("Could not prepare the request.");
            return;
        }

        BinData data = new BinData();
        try {
            data.loadFile("qa_data/files/example.bin");
        } catch (ChilkatException e) {
            System.out.println("Could not load the input file.");
            return;
        }

        StringBuilder response = new StringBuilder();
        try {
            rest.fullRequestBd("PUT", objectPath.getAsString(), data, response);
        } catch (ChilkatException e) {
            System.out.println("Upload did not complete; inspect diagnostics privately.");
            return;
        }

        String responseBody = response.getAsString();
        if (rest.getResponseStatusCode() != 200) {
            System.out.println("S3 HTTP status: " + rest.getResponseStatusCode());
            try {
                xml.loadXml(responseBody);
                success = true;
            } catch (ChilkatException e) {
                success = false;
            }
            textCompare.clear();
            textCompare.setString(xml.getTag());
            boolean sameText4 = textCompare.contentsEqual("Error", true);
            if ((success) && (sameText4)) {
                System.out.println("S3 error code: " + xml.getChildContent("Code"));
            }

            // Keep signed headers, credentials, URLs, and full diagnostics private.
            // A timeout may leave a write's outcome uncertain. Check before retrying.
            return;
        }

        System.out.println("Object uploaded.");
        System.out.println("ETag: " + rest.responseHdrByName("ETag"));
        // ETag is an opaque validator, not a universally valid MD5 checksum.
    }
}