跳至內容

請求表單和檔案

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

資訊

要接收上傳的檔案和/或表單資料,請先安裝 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,
    }
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,
    }

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

警告

您可以在一個*路徑操作*中宣告多個 FileForm 參數,但您不能同時宣告預期以 JSON 接收的 Body 欄位,因為請求的 body 將使用 multipart/form-data 編碼,而不是 application/json

這並非 FastAPI 的限制,而是 HTTP 協定的一部分。

摘要

當您需要在同一個請求中接收資料和檔案時,請一起使用 FileForm