Skip to main content

File

Declare a file upload parameter for a path operation. File parameters receive uploaded files as bytes or UploadFile objects.

Signature

Parameters

Any
default:"Undefined"
Default value if the parameter field is not set.
str
default:"multipart/form-data"
The media type of this parameter field. For file uploads, this is always multipart/form-data.
str | None
default:"None"
An alternative name for the parameter field. This will be used to extract the data and for the generated OpenAPI.
str | None
default:"None"
Human-readable title for the parameter.
str | None
default:"None"
Human-readable description for the parameter.
list[Any] | None
default:"None"
Example values for this field.
bool | str | None
default:"None"
Mark this parameter field as deprecated. It will affect the generated OpenAPI (visible at /docs).
bool
default:"True"
Whether to include this parameter field in the generated OpenAPI.
dict[str, Any] | None
default:"None"
Any additional JSON schema data.

UploadFile Class

The UploadFile class provides an async-friendly interface for working with uploaded files.

Attributes

  • filename: str - The original filename
  • content_type: str - The content type (MIME type)
  • file: SpooledTemporaryFile - The actual Python file object
  • headers: Headers - The headers associated with the file
  • size: int - The size of the file in bytes

Methods

  • async read(size: int = -1): Read the file contents
  • async write(data: bytes): Write data to the file
  • async seek(offset: int): Move to a specific position in the file
  • async close(): Close the file

Examples

Upload Single File (UploadFile)

UploadFile is recommended over bytes for file uploads because it uses a spooled file (stored in memory up to a size limit, then on disk), making it more memory-efficient for large files.

Upload Single File (bytes)

Using bytes loads the entire file into memory. This is only suitable for small files.

Upload Multiple Files

Optional File Upload

File Upload with Form Data

File Upload with Metadata

Working with UploadFile

Save File to Disk

Read File in Chunks

Process Image File

Validate File Type

Common Use Cases

Profile Picture Upload

Document Upload

Bulk File Upload

Installation Requirement

File uploads require the python-multipart package:

Important Notes

Always validate file types and sizes to prevent security issues and resource exhaustion.
UploadFile uses Python’s SpooledTemporaryFile, which stores the file in memory up to a maximum size, then stores it on disk. This makes it efficient for both small and large files.
Don’t forget to await file.read() since UploadFile methods are async.