跳到内容

UploadFile

您可以将路径操作函数参数定义为 UploadFile 类型,以从请求中接收文件。

您可以直接从 fastapi 导入它。

from fastapi import UploadFile

fastapi.UploadFile

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

基类: UploadFile

在请求中上传的文件。

将其定义为路径操作函数(或依赖项)参数。

如果您使用的是常规 def 函数,则可以使用 upload_file.file 属性来访问原始的标准 Python 文件对象(阻塞,非异步),这对非异步代码非常有用且必要。

FastAPI 请求文件文档中阅读更多相关信息。

示例

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}
源代码位于 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 实例属性

file

标准的 Python 文件对象(非异步)。

filename 实例属性

filename

原始文件名。

size 实例属性

size

文件大小(字节)。

headers 实例属性

headers

请求的头部信息。

content_type 实例属性

content_type

从头部获取的请求内容类型。

read 异步

read(size=-1)

从文件中读取字节数据。

为了支持 await 语法和异步兼容,此操作在线程池中运行。

参数 描述
size

要从文件中读取的字节数。

类型: int 默认: -1

源代码位于 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 异步

write(data)

向文件写入字节数据。

通常您不会在请求读取的文件中使用此方法。

为了支持 await 语法和异步兼容,此操作在线程池中运行。

参数 描述
data

要写入文件的字节数据。

类型: bytes

源代码位于 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 异步

seek(offset)

移动到文件中的指定位置。

随后的任何读取或写入操作都将从该位置开始。

为了支持 await 语法和异步兼容,此操作在线程池中运行。

参数 描述
offset

要在文件中查找的字节位置。

类型: int

源代码位于 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 异步

close()

关闭文件。

为了支持 await 语法和异步兼容,此操作在线程池中运行。

源代码位于 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()