How do you make an S3 object public via the aws Java SDK?

JavaApiAmazon S3Amazon Web-Services

Java Problem Overview


How do you make an S3 object public via the AWS Java SDK?

Specifically, what API methods via the Java AWS SDK can be used to make an Object public when its uploaded?

Java Solutions


Solution 1 - Java

Found the answer in an amazon aws forum.

return s3Client.putObject(
   new PutObjectRequest(bucketName, objectKey, inputStream, metadata)
      .withCannedAcl(CannedAccessControlList.PublicRead));

The answer being

.withCannedAcl(CannedAccessControlList.PublicRead)

Solution 2 - Java

An alternative approach which allows for more finegrained control of who exactly is allowed to view the object (all users or authenticated users only):

    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, image);
    AccessControlList acl = new AccessControlList();
    acl.grantPermission(GroupGrantee.AllUsers, Permission.Read); //all users or authenticated
    putObjectRequest.setAccessControlList(acl);
    s3client.putObject(putObjectRequest);

Solution 3 - Java

s3client.setObjectAcl("bucketName[/subDirectory]", fileName, CannedAccessControlList.PublicRead);
URL url = s3client.getUrl("bucketName[/subDirectory]", fileName);
String sharableLink = url.toExternalForm();

source

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMikeNeresonView Question on Stackoverflow
Solution 1 - JavaMikeNeresonView Answer on Stackoverflow
Solution 2 - JavaMauriceView Answer on Stackoverflow
Solution 3 - JavaRajatView Answer on Stackoverflow