You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pillow打开POST上传图片时遇格式异常问题求助

Fixing Pillow Image Loading for Multipart Form Uploads

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 like multipart/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 use multipart (install via pip install multipart)—but cgi is 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:53:39