跳转至

请求表单与文件

你可以同时使用 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
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,
    }

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

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

您可以在 路径操作 中声明多个 FileForm 参数,但不能同时声明期望以 JSON 形式接收的 Body 字段,因为请求的正文将使用 multipart/form-data 编码而不是 application/json

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

总结

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