Ismail9403
Ismail9403

Reputation: 69

How to save a file in a folder within a S3 bucket using Flask?

I try to save images in a folder within my s3 bucket, but it always save within the root of the bucket, not the folder. Here is what my code looks like:

s3 = boto3.client(
"s3",
aws_access_key_id = Config.S3_ACCESS_KEY,
aws_secret_access_key = Config.S3_SECRET_ACCESS_KEY
)

def upload_file_to_s3(file, acl="public-read"):
try:
    s3.upload_fileobj(
        file,
        Config.S3_BUCKET,
        file.filename,
        ExtraArgs={
            "ACL": acl,
            "ContentType": file.content_type
        }
    )

except Exception as e:
    print("Something happened: ", e)
    return e

return f"{ Config.S3_DOMAIN }profiles_name/{ file.filename }"

Profiles_name is the name of the folder. How to do I achieve this?

Upvotes: 0

Views: 450

Answers (1)

It should work for you:

s3.upload_fileobj(
        file,
        Config.S3_BUCKET,
        f"path/to/folder/within/bucket/{file.filename}",
        ExtraArgs={
            "ACL": acl,
            "ContentType": file.content_type
        }
    )

Upvotes: 1

Related Questions