Use AWS SDK for Java 2.0,Set S3 object public access

Region region = Region.AP_SOUTHEAST_1;
        s3 = S3Client.builder().region(region).build();
        

        String bucket = "your bucket name";// "bucket" + System.currentTimeMillis();
        String key = "your file name";
	    
        //create bucket if it is not exist
        createBucket(bucket, region);

        // Put Object
        PutObjectRequest request = PutObjectRequest.builder().bucket(bucket).key(key).build();
        s3.putObject(request,RequestBody.fromByteBuffer(getRandomByteBuffer(10_000)));
 
        //set public acl
        PutObjectAclRequest putAclReq = PutObjectAclRequest.builder()
        		.bucket(bucket)
        		.key(key)
        		.acl(ObjectCannedACL.PUBLIC_READ)
        		//.accessControlPolicy(acl)
        		.build();
        s3.putObjectAcl(putAclReq);
        
	//set email acl
	 // get the current ACL
        	GetObjectAclRequest objectAclReq = GetObjectAclRequest.builder()
            		.bucket(bucket_name)
            		.key(object_key)
            		.build();
		String email = "your email adress";
        	GetObjectAclResponse getAclRes = s3.getObjectAcl(objectAclReq);
            Grantee grantee = Grantee.builder().emailAddress(email).build();
            Permission permission = Permission.valueOf(Permission.Read);
            List<Grant> grants = getAclRes.grants();
            Grant newGrantee = Grant.builder()
            		.grantee(grantee)
            		.permission(permission)
            		.build();
            grants.add(newGrantee);

            //put the new acl
            AccessControlPolicy acl = AccessControlPolicy.builder()
            		.grants(grants)
            		.build();
            PutObjectAclRequest putAclReq = PutObjectAclRequest.builder()
            		.bucket(bucket_name)
            		.key(object_key)
            		.accessControlPolicy(acl)
            		.build();
            s3.putObjectAcl(putAclReq);

Leave a Comment

Your email address will not be published. Required fields are marked *