Skip to content

請求中的表單與檔案

🌐 AI 與人類共同完成的翻譯

此翻譯由人類指導的 AI 完成。🤝

可能會有對原意的誤解,或讀起來不自然等問題。🤖

你可以透過協助我們更好地引導 AI LLM來改進此翻譯。

英文版

你可以使用 FileForm 同時定義檔案與表單欄位。

Info

要接收上傳的檔案與/或表單資料,請先安裝 python-multipart

請先建立並啟用一個 虛擬環境,然後再安裝,例如:

$ pip install python-multipart

匯入 FileForm

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,
    }

定義 FileForm 參數

以與 BodyQuery 相同的方式建立檔案與表單參數:

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) 中宣告多個 FileForm 參數,但不能同時再宣告預期以 JSON 接收的 Body 欄位,因為該請求的本文會使用 multipart/form-data 而非 application/json 進行編碼。

這不是 FastAPI 的限制,這是 HTTP 通訊協定本身的規範。

小結

當你需要在同一個請求中同時接收資料與檔案時,請搭配使用 FileForm