FastAPI中如何通过BaseModel实现文件上传与数据提交?
解决FastAPI端点同时支持文件上传和表单数据的问题
错误原因
你直接在BaseModel中定义UploadFile字段并使用File(),会导致FastAPI默认将请求视为JSON格式解析。但文件上传需要使用multipart/form-data类型,JSON解析器遇到二进制文件内容时就会触发UTF-8解码错误。
正确实现方式
要通过BaseModel同时处理文件和其他表单数据,需要配置模型支持任意类型,并让FastAPI正确识别multipart/form-data中的各个字段。
完整代码示例
from fastapi import FastAPI, UploadFile, Depends from pydantic import BaseModel, Field app = FastAPI() class ExampleRequest(BaseModel): image: UploadFile = Field(..., description="上传的图片文件") transaction_id: str = Field(None, description="交易ID") organization_id: str = Field(None, description="组织ID") class Config: # 允许UploadFile这类非标准Pydantic类型 arbitrary_types_allowed = True @app.post("/example") async def handle_example(request: ExampleRequest = Depends()): # 读取文件内容(可选操作) file_content = await request.image.read() # 返回处理结果 return { "filename": request.image.filename, "transaction_id": request.transaction_id, "organization_id": request.organization_id, "file_size_bytes": len(file_content) }
请求示例
使用curl发送multipart/form-data请求:
curl -X POST "http://localhost:8000/example" \ -F "image=@your_image_file.jpg" \ -F "transaction_id=TXN12345" \ -F "organization_id=ORG67890"
另一种简化写法(无需BaseModel)
如果不需要强制用BaseModel,可以直接在端点参数中结合File()和Form(),这种方式更直观:
from fastapi import FastAPI, UploadFile, File, Form app = FastAPI() @app.post("/example") async def handle_example( image: UploadFile = File(...), transaction_id: str = Form(None), organization_id: str = Form(None) ): return { "filename": image.filename, "transaction_id": transaction_id, "organization_id": organization_id }
内容的提问来源于stack exchange,提问作者Sedat Unal
相关产品推荐
相关产品推荐

