【问题标题】:How to add metadata while using boto3 create_presigned_post?如何在使用 boto3 create_presigned_post 时添加元数据?
【发布时间】:2020-11-07 16:20:13
【问题描述】:

想要将自定义元数据添加到我使用 create_presigned_post 从 boto3 上传的文件中。我正在运行以下代码,但收到 403 响应。下面的代码是从here借来的。我做错了吗?

def create_presigned_post(bucket_name, object_name,
                          fields=None, conditions=None, expiration=3600):

    # Generate a presigned S3 POST URL
    s3_client = boto3.client('s3')
    try:
        response = s3_client.generate_presigned_post(bucket_name,
                                                     object_name,
                                                     Fields=fields,
                                                     Conditions=conditions,
                                                     ExpiresIn=expiration)
    except ClientError as e:
        print(e)
        return None

    # The response contains the presigned URL and required fields
    return response

# Generate a presigned S3 POST URL
object_name = 'test-file.txt'
response = create_presigned_post('temp', object_name, fields={'x-amz-meta-test_key': 'test_val'})

# Demonstrate how another Python program can use the presigned URL to upload a file
with open('test-file.txt', 'rb') as f:
    files = {'file': (object_name, f)}
    http_response = requests.post(response['url'], data=response['fields'], files=files)
# If successful, returns HTTP status code 204
print(f'File upload HTTP status code: {http_response.status_code}')

【问题讨论】:

    标签: amazon-s3 metadata boto3 http-status-code-403 pre-signed-url


    【解决方案1】:

    As per document,字段字典不会自动添加到条件列表中。您还必须为元素指定条件。

    response = create_presigned_post(bucket_name, object_name, fields={'x-amz-meta-test_key': 'test-val'}, conditions=[{'x-amz-meta-test_key': 'test-val'}])
    

    它应该工作:)

    【讨论】:

    • 谢谢!它就像一个魅力! :) 我没有从文档中得到。我认为条件是用于过滤某些字段。
    猜你喜欢
    • 2021-12-11
    • 2016-02-19
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 2021-12-08
    • 1970-01-01
    • 2019-11-23
    相关资源
    最近更新 更多