请求表单和文件¶
您可以使用 File 和 Form 同时定义文件和表单字段。
导入 File 和 Form¶
from typing import Annotated
from fastapi import FastAPI, File, Form, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(
file: Annotated[bytes, File()],
fileb: Annotated[UploadFile, File()],
token: Annotated[str, Form()],
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
🤓 其他版本和变体
提示
如果可能,请优先使用 Annotated 版本。
from fastapi import FastAPI, File, Form, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(
file: bytes = File(), fileb: UploadFile = File(), token: str = Form()
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
定义 File 和 Form 参数¶
创建文件和表单参数的方式与创建 Body 或 Query 参数的方式相同。
from typing import Annotated
from fastapi import FastAPI, File, Form, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(
file: Annotated[bytes, File()],
fileb: Annotated[UploadFile, File()],
token: Annotated[str, Form()],
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
🤓 其他版本和变体
提示
如果可能,请优先使用 Annotated 版本。
from fastapi import FastAPI, File, Form, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(
file: bytes = File(), fileb: UploadFile = File(), token: str = Form()
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
文件和表单字段将作为表单数据上传,您将接收到这些文件和表单字段。
您可以将一些文件声明为 bytes,一些声明为 UploadFile。
警告
您可以在一个路径操作中声明多个 File 和 Form 参数,但不能同时声明您期望作为 JSON 接收的 Body 字段,因为请求的主体将使用 multipart/form-data 而不是 application/json 进行编码。
这不是 FastAPI 的限制,它是 HTTP 协议的一部分。
总结¶
当您需要在同一个请求中接收数据和文件时,请同时使用 File 和 Form。