Ayisha mehrin
Ayisha mehrin

Reputation: 45

how to upload files to separate folders in aws3 bucket

i want to upload public files to public folder and private files to private folder created in aws3 bucket.

What changes should I make in the code.

@Override
public void uploadFile(String keyName, String uploadFilePath) {
    try {
        File file = new File(uploadFilePath);
        s3client.putObject(new PutObjectRequest(bucketName + "/public", keyName, file));
        logger.info("===================== Upload File - Done! =====================");
        System.out.println("url is*****" + s3client.getUrl(bucketName + "/public", keyName).toString());
        url = s3client.getUrl(bucketName+ "/public", keyName).toString();
        Connection cn = new Connection();
        cn.db();
    } catch (AmazonServiceException ase) {
        logger.info("Caught an AmazonServiceException from PUT requests, rejected reasons:");
        logger.info("Error Message:    " + ase.getMessage());
        logger.info("HTTP Status Code: " + ase.getStatusCode());
        logger.info("AWS Error Code:   " + ase.getErrorCode());
        logger.info("Error Type:       " + ase.getErrorType());
        logger.info("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        logger.info("Caught an AmazonClientException: ");
        logger.info("Error Message: " + ace.getMessage());
    }
}

Upvotes: 1

Views: 251

Answers (2)

John Rotenstein
John Rotenstein

Reputation: 269951

By default, all objects in an Amazon S3 bucket are private.

If you then wish to make a particular folder public, you would use a Bucket Policy, such as:

{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"PublicFolder",
      "Effect":"Allow",
      "Principal": "*",
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::examplebucket/public/*"]
    }
  ]
}

Upvotes: 1

Michael - sqlbot
Michael - sqlbot

Reputation: 179294

Incorrect construction of values for bucket, key:

bucketName + "/public", keyName

Correct construction of values for bucket, key:

bucketName, "public/" + keyName

Note that the object key should not have included a leading /, so if your keyName has one now, then that is wrong and should be fixed... object keys do not have a leading / and supplying one will cause problems.

Upvotes: 1

Related Questions