How do I set file permissions for files in a space using AWS SDK with java?

Posted January 20, 2020 685 views

I am using a space to store images for my web app. Those images need to be public so I can display them on the web app. How do I make those images public using the AWS SDK with Java? I know how to do it manually but obviously that is not scalable.

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
3 answers

The above answer does not really help. I figured it out on my own and here is the code snippet in case anybody else has this question.

AmazonS3 awsBuckets =
            .withEndpointConfiguration(new EndpointConfiguration(bucketUrl, "nyc3"))

PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, converted);

edited by MattIPv4


I have not done this with Java, but usually with Laravel for example, what I would do is to sue the putFile method, which allows you to pass the this as an argument:

Storage::disk('spaces')->putFile('uploads', request()->file, 'public');

In your case what I could suggest is setting the x-amz-acl header to public-read that way each individual file would be available for everyone. For more information you could take a look at the documentation here:

Or another option would be to set your listing permissions to public so that all files in that listing would be available by default:

Hope that this helps!

This worked for me

public String uploadBase64ToStorage(String filePath,String location,String fileName) {

        String key = Config.getProperty("spaces", "key");
        String secret = Config.getProperty("spaces", "secret");
        String bucket = Config.getProperty("spaces", "bucket");
        String endpoint = Config.getProperty("spaces", "endpoint");
        String region = Config.getProperty("spaces", "region");

        AWSCredentialsProvider awscp = new AWSStaticCredentialsProvider(
                new BasicAWSCredentials(key, secret)
        AmazonS3 space = AmazonS3ClientBuilder
                        new AwsClientBuilder.EndpointConfiguration(endpoint, region)

        File file = new File(filePath);

        String filepath = location+"/"+fileName; // /somefolder/someanotherfolder/testfile.jpg";

        ObjectMetadata om = new ObjectMetadata();

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket,filepath,file).withCannedAcl(CannedAccessControlList.PublicRead);

        return space.getUrl(bucket, filepath).toString();