You need to enable JavaScript to run this app. 如何在boto3 create_presigned_post中添加自定义元数据?返回403错误怎么办
优惠活动
大模型
产品
解决方案
定价
更多

如何在boto3 create_presigned_post中添加自定义元数据?返回403错误怎么办

403报错核心原因

预签名POST的字段校验规则不匹配,和自定义元数据的配置方式直接相关,具体问题有两点:

  • 仅将自定义元数据放入Fields参数不符合S3的校验逻辑:所有在Fields中预设的字段,必须同时在Conditions参数中明确声明允许规则,否则上传请求会被判定为未授权,直接返回403。
  • 缺少对应字段校验规则时,S3会认为提交的x-amz-meta-*自定义字段不在允许上传的字段列表内,拒绝处理请求。
修正后的可运行代码
import boto3
from botocore.exceptions import ClientError
import requests

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

# 预签名配置
object_name = 'test-file.txt'
# 自定义元数据:注意key不能使用下划线,需符合S3命名规范
custom_fields = {'x-amz-meta-test-key': 'test_val'}
# 必须在条件列表中声明对应元数据的校验规则
custom_conditions = [
    # 固定值匹配规则
    {"x-amz-meta-test-key": "test_val"}
]

# 生成预签名信息
response = create_presigned_post(
    'temp',
    object_name,
    fields=custom_fields,
    conditions=custom_conditions
)

# 上传逻辑无需修改:requests会自动携带预签名返回的所有表单字段(含自定义元数据)
with open('test-file.txt', 'rb') as f:
    files = {'file': (object_name, f)}
    http_response = requests.post(response['url'], data=response['fields'], files=files)

# 成功时返回204状态码
print(f'File upload HTTP status code: {http_response.status_code}')
常见踩坑提示
  • S3自定义元数据的key不允许使用下划线,原代码中的x-amz-meta-test_key属于不合法命名,建议替换为短横线分隔的格式,避免触发额外的校验错误。
  • 如果不需要固定元数据值,可以将条件替换为前缀匹配规则,允许任意非空值的该字段:["starts-with", "$x-amz-meta-test-key", ""]。
  • 预签名生成后不要修改response['fields']中的内容,否则会破坏签名校验,直接导致403报错。

内容的提问来源于stack exchange,提问作者amey uchagaonkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.12.05 23:36:03