When I tried uploading an image to s3 using boto3 in python I am constantly getting errors. The error says:
An error occurred (AccessDenied) when calling the PutObject operation: Access Denied
My code for uploading the image is
def upload_file(file_name, bucket, object_name=None):
"""Upload a file to an S3 bucket
:param file_name: File to upload
:param bucket: Bucket to upload to
:param object_name: S3 object name. If not specified then file_name is used
:return: True if file was uploaded, else False
"""
# If S3 object_name was not specified, use file_name
if object_name is None:
object_name = file_name
# Upload the file
s3_client = boto3.client('s3')
try:
response = s3_client.upload_file(file_name, bucket, object_name, ExtraArgs={'ACL':'public-read'})
print(response)
except Exception as e:
print(e)
return False
return True
The solution was very simple and easy, since I was not providing the ACCESS_KEY & SECRET_KEY, so AWS was not letting me upload image to s3.
I added both the access key and secret key to it while getting the client of s3 from boto3
s3_client = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
A good documentation of this is present at boto documentation