Sample code for 30+ languages & platforms
Java

S3 Upload Binary File from BinData

See more Amazon S3 (new) Examples

Upload a binary file contained in a BinData object to Amazon S3.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.AuthAws;
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Rest;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        // This example requires the Chilkat API to have been previously unlocked.
        // See Global Unlock Sample for sample code.

        Rest rest = new Rest();

        // Connect to the Amazon AWS REST server.
        boolean bTls = true;
        int port = 443;
        boolean bAutoReconnect = true;
        // Make sure to connect to the region where the bucket is located..
        rest.connect("s3-us-west-2.amazonaws.com", port, bTls, bAutoReconnect);

        // Provide AWS credentials for the REST call.
        AuthAws authAws = new AuthAws();
        authAws.setAccessKey("AWS_ACCESS_KEY");
        authAws.setSecretKey("AWS_SECRET_KEY");
        // Use the correct region..
        authAws.setRegion("us-west-2");
        authAws.setServiceName("s3");

        rest.setAuthAws(authAws);

        // Set the bucket name via the HOST header.
        // In this case, the bucket name is "chilkat.qa".
        // (Also make sure to use the correct region.)
        rest.setHost("chilkat.qa.s3-us-west-2.amazonaws.com");

        // Load a text file into memory.
        BinData pngData = new BinData();
        try {
            pngData.loadFile("qa_data/png/anemone.png");
        } catch (ChilkatException e) {
            System.out.println("Failed to load file from local filesystem.");
            return;
        }

        // Indicate the Content-Type of our upload.  (This is optional)
        rest.addHeader("Content-Type", "image/png");

        // Upload the file to Amazon S3.
        StringBuilder sbResponse = new StringBuilder();
        try {
            rest.fullRequestBd("PUT", "/images/sea_creatures/anemone.png", pngData, sbResponse);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Did we get a 200 response indicating success?
        int statusCode = rest.getResponseStatusCode();
        if (statusCode != 200) {
            System.out.println("Error response: " + sbResponse.getAsString());
            System.out.println("Status code: " + statusCode + ", Status text: " + rest.getResponseStatusText());
            return;
        }

        System.out.println("File successfully uploaded.");
    }
}