使用Pillow打开POST上传图片时遇格式异常问题求助
Hey there! I see exactly what's going wrong here—your POST request body isn't just raw image data, it's wrapped in multipart/form-data formatting (those --------------------------332c61f93bcd60b4 boundary lines and Content-Disposition headers are dead giveaways). You can't feed this directly to Pillow because it expects pure image bytes, not the full HTTP form payload with metadata.
Let's break down how to fix this:
1. Why Your Current Code Fails
When you upload a file via a form, the client wraps the image in multipart boundaries and descriptive headers. Your current code decodes the base64 body but doesn't strip away that extra form data—so Pillow tries to parse those text headers as part of the image, which breaks immediately.
2. Working Solution Code
We'll decode the base64 data first, then parse the multipart form to extract only the raw image bytes:
import io import base64 import cgi from PIL import Image # Decode the base64-encoded request body to get raw multipart data raw_multipart_data = base64.b64decode(event["body"]) # Parse the multipart form using Python's built-in cgi module form_data = cgi.FieldStorage( fp=io.BytesIO(raw_multipart_data), headers={"Content-Type": event["headers"]["Content-Type"]}, environ={"REQUEST_METHOD": "POST"} ) # Extract the image content from the "image" form field image_bytes = form_data.getvalue("image") if not image_bytes: raise ValueError("No 'image' field found in the uploaded form data") # Now we can open the image with Pillow correctly img = Image.open(io.BytesIO(image_bytes)) # Optional: Verify the image loads (e.g., display it) # img.show()
Key Details to Keep in Mind
- Content-Type Header: Double-check that
event["headers"]["Content-Type"]includes the multipart boundary (it should look likemultipart/form-data; boundary=--------------------------332c61f93bcd60b4). This boundary string is how the parser knows where the image data starts and ends. - Alternative Parsers: If you prefer a more modern library over
cgi, you can usemultipart(install viapip install multipart)—butcgiis part of Python's standard library and works perfectly for standard cases. - Framework Context: If you're using a web framework like Flask or FastAPI, they handle multipart parsing automatically—this code is tailored for environments where you're dealing with raw request events (like AWS Lambda).
内容的提问来源于stack exchange,提问作者Gianmarco Carrieri

