콘텐츠로 이동

폼 및 파일 요청

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,
    }
🤓 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로 선언할 수 있습니다.

경고

다수의 FileForm 매개변수를 한 경로 처리에 선언하는 것이 가능하지만, 요청의 본문이 application/json가 아닌 multipart/form-data로 인코딩되기 때문에 JSON으로 받기를 기대하는 Body 필드를 함께 선언할 수는 없습니다.

이는 FastAPI의 한계가 아니라, HTTP 프로토콜의 일부입니다.

요약

하나의 요청으로 데이터와 파일들을 받아야 할 경우 FileForm을 함께 사용하기 바랍니다.