Sandip Dhang
Sandip Dhang

Reputation: 285

How to add public access for the images while uploading images to AWS S3

I am new to AWS. I have a web app with two pages One page to upload an image to an s3 bucket and another page displaying that image. I have successfully set up the AWS S3 upload function with 'aws-sdk' as I'm using node backend.

Files uploading is successful also I'm getting the URL after upload but the issue is when I try to get the image from the URL it throws 'Access Denied'. I found that after every upload I need to to to that file on the S3 console and enable public access to access the file with that previous responded link.

I have already enabled public access for the whole bucket.

So my question is: Is there any way to enable permission while uploading so that I can after every upload I don't need to enable it to access that file?

Upvotes: 6

Views: 2298

Answers (2)

Sandip Dhang
Sandip Dhang

Reputation: 285

This works for me

const s3Params = {
    Bucket: process.env.AWS_BUCKET_NAME,
    Key: `${fileName}.${fileType}`,
    Body: req.file.buffer,
    ACL: "public-read", // enable public access for this object
  };

Upvotes: 9

Vidura Dantanarayana
Vidura Dantanarayana

Reputation: 531

If you want to enable this for every object in the bucket, try adding this bucket policy.

{
  "Id": "Policy1623923889950",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1623923886911",
      "Action": [
        "s3:GetObject"
      ],
      "Effect": "Allow",
      "Resource": "arn:aws:s3:::yourbucket",
      "Principal": "*"
    }
  ]

}

Upvotes: 0

Related Questions