跳至内容

请求表单和文件

您可以使用 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