請求中的表單與檔案¶
你可以使用 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,
}
🤓 Other versions and variants
Tip
Prefer to use the Annotated version if possible.
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,
}
🤓 Other versions and variants
Tip
Prefer to use the Annotated version if possible.
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。
Warning
你可以在一個路徑操作 (path operation) 中宣告多個 File 與 Form 參數,但不能同時再宣告預期以 JSON 接收的 Body 欄位,因為該請求的本文會使用 multipart/form-data 而非 application/json 進行編碼。
這不是 FastAPI 的限制,這是 HTTP 通訊協定本身的規範。
小結¶
當你需要在同一個請求中同時接收資料與檔案時,請搭配使用 File 與 Form。