Saltar al contenido

Clase UploadFile

Puedes definir parámetros de función de operación de path para que sean del tipo UploadFile para recibir archivos de la petición.

Puedes importarlo directamente desde fastapi:

from fastapi import UploadFile

fastapi.UploadFile

UploadFile(file, *, size=None, filename=None, headers=None)

Hereda de: UploadFile

Un archivo subido en una petición.

Defínelo como un parámetro de función de operación de path (o dependencia).

Si estás usando una función def regular, puedes usar el atributo upload_file.file para acceder al archivo estándar de Python crudo (bloqueante, no async), útil y necesario para código no async.

Lee más sobre esto en la documentación de FastAPI para Archivos de Petición.

Ejemplo

from typing import Annotated

from fastapi import FastAPI, File, UploadFile

app = FastAPI()


@app.post("/files/")
async def create_file(file: Annotated[bytes, File()]):
    return {"file_size": len(file)}


@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile):
    return {"filename": file.filename}
Código fuente en starlette/datastructures.py
def __init__(
    self,
    file: BinaryIO,
    *,
    size: int | None = None,
    filename: str | None = None,
    headers: Headers | None = None,
) -> None:
    self.filename = filename
    self.file = file
    self.size = size
    self.headers = headers or Headers()

    # Capture max size from SpooledTemporaryFile if one is provided. This slightly speeds up future checks.
    # Note 0 means unlimited mirroring SpooledTemporaryFile's __init__
    self._max_mem_size = getattr(self.file, "_max_size", 0)

file instance-attribute

file

El objeto de archivo estándar de Python (no async).

filename instance-attribute

filename

El nombre original del archivo.

size instance-attribute

size

El tamaño del archivo en bytes.

headers instance-attribute

headers

Los headers de la petición.

content_type instance-attribute

content_type

El content type de la petición, desde los headers.

read async

read(size=-1)

Leer algunos bytes del archivo.

Para ser awaitable, compatible con async, esto se ejecuta en un threadpool.

PARÁMETRO DESCRIPCIÓN
size

El número de bytes a leer del archivo.

TIPO: int DEFAULT: -1

Código fuente en fastapi/datastructures.py
async def read(
    self,
    size: Annotated[
        int,
        Doc(
            """
            The number of bytes to read from the file.
            """
        ),
    ] = -1,
) -> bytes:
    """
    Read some bytes from the file.

    To be awaitable, compatible with async, this is run in threadpool.
    """
    return await super().read(size)

write async

write(data)

Escribir algunos bytes al archivo.

Normalmente no usarías esto con un archivo que lees en una petición.

Para ser awaitable, compatible con async, esto se ejecuta en un threadpool.

PARÁMETRO DESCRIPCIÓN
data

Los bytes a escribir al archivo.

TYPE: bytes

Código fuente en fastapi/datastructures.py
async def write(
    self,
    data: Annotated[
        bytes,
        Doc(
            """
            The bytes to write to the file.
            """
        ),
    ],
) -> None:
    """
    Write some bytes to the file.

    You normally wouldn't use this from a file you read in a request.

    To be awaitable, compatible with async, this is run in threadpool.
    """
    return await super().write(data)

seek async

seek(offset)

Moverse a una posición en el archivo.

Cualquier próxima lectura o escritura se hará desde esa posición.

Para ser awaitable, compatible con async, esto se ejecuta en un threadpool.

PARÁMETRO DESCRIPCIÓN
offset

La posición en bytes a la que moverse en el archivo.

TIPO: int

Código fuente en fastapi/datastructures.py
async def seek(
    self,
    offset: Annotated[
        int,
        Doc(
            """
            The position in bytes to seek to in the file.
            """
        ),
    ],
) -> None:
    """
    Move to a position in the file.

    Any next read or write will be done from that position.

    To be awaitable, compatible with async, this is run in threadpool.
    """
    return await super().seek(offset)

close async

close()

Cerrar el archivo.

Para ser awaitable, compatible con async, esto se ejecuta en un threadpool.

Código fuente en fastapi/datastructures.py
async def close(self) -> None:
    """
    Close the file.

    To be awaitable, compatible with async, this is run in threadpool.
    """
    return await super().close()