Sourav
Sourav

Reputation: 91

Uploading File to a specific location in Amazon S3 Bucket using boto3?

I am trying to upload few files into Amazon S3. I am able to upload the file in my bucket. However, the file needs to be in my-bucket-name,Folder1/Folder2.

import boto3
from boto.s3.key import Key
session = boto3.Session(aws_access_key_id=AWS_ACCESS_KEY_ID, 
aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
bucket_name = 'my-bucket-name'
prefix = 'Folder1/Folder2'
s3 = session.resource('s3')
bucket = s3.Bucket(bucket_name)
objs = bucket.objects.filter(Prefix=prefix)

I tried to upload into bucket using this code and succeeded:

s3.meta.client.upload_file('C:/hello.txt', bucket, 'hello.txt')

When I tried to upload the same file into specified Folder2 using this code the failed with error:

s3.meta.client.upload_file('C:/hello.txt', objs, 'hello.txt')

ERROR>>>
botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid bucket name "s3.Bucket.objectsCollection(s3.Bucket(name='my-bucket-name'), s3.ObjectSummary)": Bucket name must match the regex "^[a-zA-Z0-9.\-_]{1,255}$"

So, how can I upload the file into my-bucket-name,Folder1/Folder2?

Upvotes: 0

Views: 3827

Answers (1)

Himanshu Bansal
Himanshu Bansal

Reputation: 2093

s3.meta.client.upload_file('C:/hello.txt', objs, 'hello.txt')

What's happening here is that the bucket argument to the client.upload_file needs to be the name of the bucket as a string

For specific folder

upload_file('C:/hello.txt', bucket, 'Folder1/Folder2/hello.txt')

Upvotes: 1

Related Questions