跳到内容

请求表单和文件

你可以使用 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 字段,因为请求主体将使用 multipart/form-data 而不是 application/json 进行编码。

这并非 FastAPI 的限制,而是 HTTP 协议的一部分。

总结

当你需要在同一个请求中接收数据和文件时,请同时使用 FileForm