生成策略与签名实现HTML POST直传Amazon S3桶报错排查
Fixing the TypeError for S3 Policy and Signature Generation
The error TypeError: a bytes-like object is required, not 'dict' pops up because you’re trying to base64-encode a Python dictionary directly—base64 only works on byte objects, not native data structures like dicts. Here’s how to fix this step by step:
Why the Error Happens
AWS expects the policy document to be a minified UTF-8 JSON string (no extra whitespace) converted to bytes before base64 encoding. Your original code skips converting the dict to JSON bytes, hence the type mismatch.
Corrected Code with Explanations
import base64 import hmac import hashlib import json # Add JSON handling import AWS_SECRET_ACCESS_KEY = 'AKIAIHHMU7Y4L2INOFRQ' policy_document = { "expiration": "2019-01-01T00:00:00Z", "conditions": [ {"bucket": "report-generation1"}, ["starts-with", "$key", ""], {"acl": "private"}, {"success_action_redirect": "localhost/"}, # Fixed trailing semicolon typo ["starts-with", "$Content-Type", ""], ["content-length-range", 0, 1048576] ] } # Step 1: Convert policy dict to minified JSON (required by AWS) policy_json = json.dumps(policy_document, separators=(',', ':')) # Step 2: Encode JSON string to UTF-8 bytes policy_bytes = policy_json.encode('utf-8') # Step 3: Base64 encode the bytes policy = base64.b64encode(policy_bytes) # Step 4: Encode secret key to bytes (HMAC requires byte input) secret_key_bytes = AWS_SECRET_ACCESS_KEY.encode('utf-8') # Step 5: Generate HMAC-SHA1 signature and base64 encode it signature = base64.b64encode(hmac.new(secret_key_bytes, policy, hashlib.sha1).digest()) # Optional: Convert to strings for easy use in HTML form fields policy_str = policy.decode('utf-8') signature_str = signature.decode('utf-8')
Key Fixes & Notes
- The
separators=(',', ':')injson.dumpsremoves extra whitespace from the JSON, which is mandatory for AWS to validate the policy. - Fixed a typo in
success_action_redirect(removed the trailing semicolon inside the string). - Converted the final policy and signature to strings so you can directly insert them into your HTML POST form’s hidden fields.
内容的提问来源于stack exchange,提问作者mrunal
相关产品推荐
相关产品推荐

