Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a file to S3 and make it public using boto3?

I am able to upload an image file using:

s3 = session.resource('s3') bucket = s3.Bucket(S3_BUCKET) bucket.upload_file(file, key) 

However, I want to make the file public too. I tried looking up for some functions to set ACL for the file but seems like boto3 have changes their API and removed some functions. Is there a way to do it in the latest release of boto3?

like image 869
Adi Avatar asked Jan 27 '17 23:01

Adi


People also ask

Can you upload to public S3 bucket?

You can have an unlimited number of objects in a bucket. Before you can upload files to an Amazon S3 bucket, you need write permissions for the bucket. For more information about access permissions, see Identity and access management in Amazon S3. You can upload any file type—images, backups, data, movies, etc.


2 Answers

To upload and set permission to publicly-readable in one step, you can use:

bucket.upload_file(file, key, ExtraArgs={'ACL':'public-read'})

See https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-uploading-files.html#the-extraargs-parameter

like image 159
Bill Baker Avatar answered Oct 10 '22 03:10

Bill Baker


I was able to do it using objectAcl API:

s3 = boto3.resource('s3') object_acl = s3.ObjectAcl('bucket_name','object_key') response = object_acl.put(ACL='public-read') 

For details: http://boto3.readthedocs.io/en/latest/reference/services/s3.html#objectacl

like image 34
Adi Avatar answered Oct 10 '22 01:10

Adi