请求表单和文件¶
你可以使用 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,
}
🤓 其他版本和变体
from fastapi import FastAPI, File, Form, UploadFile
from typing_extensions import Annotated
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,
}
🤓 其他版本和变体
from fastapi import FastAPI, File, Form, UploadFile
from typing_extensions import Annotated
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
。