Java – Use the AWS SDK to upload files to S3

Use the AWS SDK to upload files to S3… here is a solution to the problem.

Use the AWS SDK to upload files to S3

I’m trying to upload a file to an Amazon S3 bucket using the AWS SDK.

class LogToS3Bucket extends Thread{

    public void run() {
        super.run();
        Gdx.app.log("msg", "secondThreadRunning yeahhhhh!");
        File fileToPut = new File("../../../MyProject", "settings.txt");
        String accessKey = "<accessKey>";
        String secretKey = "<secretKey>";
        AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        AmazonS3 conn = new AmazonS3Client(credentials);

        conn.putObject("bucketname", "filename.txt", fileToPut);
    }

}

While it doesn’t work, it throws an error when .putObject() is called

Exception in thread "Thread-1" Status Code: 400, AWS Service: Amazon S3, AWS Error Code: BadDigest, AWS Error Message: The Content-MD5 you specified did not match what we received.
    at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:614)
    at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:312)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:165)
    at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:2951)
    at com.amazonaws.services.s3.AmazonS3Client.putObject(AmazonS3Client.java:1123)
    at com.amazonaws.services.s3.AmazonS3Client.putObject(AmazonS3Client.java:979)
    at com.myproject.LogToS3Bucket.run(LogToS3Bucket.java:22)

Best Solution

I think I get it – because my app keeps editing that file, and this fragment happens in a separate thread, the file is actually changed before it’s uploaded… If I make a temporary copy of a file and upload it to the bucket, it works.