コンテンツへスキップ

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 のソースコード
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
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

標準のPythonファイルオブジェクト (非同期)。

filename instance-attribute

filename

元のファイル名。

size instance-attribute

size

ファイルのサイズ (バイト単位)。

headers instance-attribute

headers

リクエストのヘッダー。

content_type instance-attribute

content_type

ヘッダーからのリクエストのコンテンツタイプ。

read async

read(size=-1)

ファイルからいくつかのバイトを読み取ります。

非同期に対応するために、これはスレッドプールで実行されます。

パラメータ 説明
size

ファイルから読み取るバイト数。

型: int デフォルト: -1

fastapi/datastructures.py のソースコード
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
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)

ファイルにいくつかのバイトを書き込みます。

通常、リクエストで読み取ったファイルからこれを使用することはありません。

非同期に対応するために、これはスレッドプールで実行されます。

パラメータ 説明
data

ファイルに書き込むバイト。

型: bytes

fastapi/datastructures.py のソースコード
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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)

ファイル内の位置に移動します。

次回の読み書きはその位置から行われます。

非同期に対応するために、これはスレッドプールで実行されます。

パラメータ 説明
offset

ファイル内でシークするバイト単位の位置。

型: int

fastapi/datastructures.py のソースコード
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
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()

ファイルを閉じます。

非同期に対応するために、これはスレッドプールで実行されます。

fastapi/datastructures.py のソースコード
131
132
133
134
135
136
137
async def close(self) -> None:
    """
    Close the file.

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