【问题标题】:Uploading File to a specific location in Amazon S3 Bucket using boto3?使用 boto3 将文件上传到 Amazon S3 存储桶中的特定位置?
【发布时间】:2019-01-22 21:00:57
【问题描述】:

我正在尝试将几个文件上传到 Amazon S3。我可以将文件上传到我的存储桶中。但是,该文件需要在 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)

我尝试使用此代码上传到存储桶并成功:

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

当我尝试使用此代码将相同的文件上传到指定的 Folder2 时,失败并出现错误:

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}$"

那么,如何将文件上传到 my-bucket-name,Folder1/Folder2?

【问题讨论】:

    标签: python amazon-s3 boto3


    【解决方案1】:

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

    这里发生的情况是,client.upload_file 的存储桶参数需要是存储桶的名称作为字符串

    针对特定文件夹

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

    【讨论】:

    • 按照您建议的方式进行操作时,我收到了这个特殊错误:文件“C:\Program Files (x86)\Python37-32\lib\site-packages\botocore\handlers.py” ,第 219 行,如果 VALID_BUCKET.search(bucket) 为 None,则在 validate_bucket_name 中:TypeError: expected string or bytes-like object
    • 我评论了上传代码并尝试查看 Bucket 是否正常工作。添加此行后,Bucket 工作正常。我收到此错误。
    • @Sourav 你能提供你试过的代码的截图和你收到的错误吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 2012-12-28
    • 1970-01-01
    • 2015-05-05
    相关资源
    最近更新 更多