首页 > 解决方案 > 如何使用 python 3.8 将文件上传到 AWS S3 子文件夹?

问题描述

我想将文件上传到 AWS S3 中存储桶中的子文件夹。我正在使用下面给出的代码。

filename  = '/tmp/' + 'image' + '.png'
file_obj = open(filename, 'rb')
s3_upload = s3.put_object( Bucket="aaa/Bbb/cc-cc", Key="filename.png", Body=file_obj)
   
return
    {
    'statusCode': 200,
    'body': json.dumps("Executed Successfully"
    }

将文件上传到 AWS S3 Bucket 的子文件夹的上述概念可以正常工作,Node.js但在实施时python会出现以下错误。

Parameter validation failed:\nInvalid bucket name \"aaa/Bbb/cc-cc\": Bucket name must match the regex \"^[a-zA-Z0-9.\\-_]{1,255}$\" or be an ARN matching the regex \"^arn:(aws).*:s3:[a-z\\-0-9]+:[0-9]{12}:accesspoint[/:][a-zA-Z0-9\\-]{1,63}$|^arn:(aws).*:s3-outposts:[a-z\\-0-9]+:[0-9]{12}:outpost[/:][a-zA-Z0-9\\-]{1,63}[/:]accesspoint[/:][a-zA-Z0-9\\-]{1,63}$\"

标签: python-3.xamazon-web-servicesamazon-s3

解决方案


在您的情况下,存储桶名称只是aaa,而/Bbb/cc-cc应该是键名的一部分:

s3_upload = s3.put_object( Bucket="aaa", Key="/Bbb/cc-cc/filename.png", Body=file_obj)

推荐阅读