Amazon S3 Access image by url

Viewed 124721

I have uploaded an image to Amazon S3 storage. But how can I access this image by url? I have made the folder and file public but still get AccessDenied error if try to access it by url https://s3.amazonaws.com/bucket/path/image.png

14 Answers

in my case i have uploaded image privately so that i was unable to access. i did following code

const AWS = require('aws-sdk')
const myBucket = 'BUCKET_NAME'
  const myKey = 'FILE_NAME.JPG'
  const signedUrlExpireSeconds = 60 * 1
  const s3 = new AWS.S3({
    accessKeyId: "ACCESS_KEY_ID",
    signatureVersion: 'v4',
    region: 'S3_REGION',
    secretAccessKey: "ACCESS_SECRET"
  });

  const url = s3.getSignedUrl('getObject', {
      Bucket: myBucket,
      Key: myKey,
      Expires: signedUrlExpireSeconds
  })

  console.log(url)

One of easiest way is to make a bucket policy.

 {
       "Version": "2012-10-17",
       "Statement": [{
           "Sid": "MakeItPublic",
           "Effect": "Allow",
           "Principal": "*", 
           "Action": "s3:GetObject",
           "Resource": "arn:aws:s3:::yourbucketname.com/*"
    }]
   }

For future reference, if you want to access a file in Amazon S3 the URL needs to be something like:

bucketname.s3.region.amazonaws.com/foldername/image.png

Example: my-awesome-bucket.s3.eu-central-1.amazonaws.com/media/img/dog.png

Don't forget to set the object to public.

Inside S3 if you click on the object will you see a field called: Object URL. That's the object's web address.

Just add Permission to follow the below image.

Justa add Permission

To access private images via URL you must provide Query-string authentication. Query-string authentication version 4 requires the X-Amz-Algorithm, X-Amz-Credential, X-Amz-Signature, X-Amz-Date, X-Amz-SignedHeaders, and X-Amz-Expires parameters.

Just addon to @akotian answer, you can get the object URL by clicking the object as follows get object url

and to access publically you can set the ACL programmatically while uploading the object to the bucket

i.e sample java request

PutObjectRequest putObjectRequest = PutObjectRequest.builder()
            .contentType(contentType)
            .bucket(LOGO_BUCKET_NAME)
            .key(LOGO_FOLDER_PREFIX+fileName)
            .acl(ObjectCannedACL.PUBLIC_READ)// this make public read
            .metadata(metadata)
            .build();
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": [
                "s3:GetObject",
                "s3:GetObjectVersion"
            ],
            "Resource": [
                "arn:aws:s3:::DOC-EXAMPLE-BUCKET/*"
            ]
        }
    ]
}

use this policy for that bucket, which makes it public.

Related