Skip to main content

UploadFile

A file uploaded in a request. Define it as a path operation function parameter or dependency to receive uploaded files. For regular def functions, you can use the upload_file.file attribute to access the raw standard Python file (blocking, not async).

Attributes

BinaryIO
The standard Python file object (non-async). Useful for non-async code.
str | None
The original file name sent by the client.
int | None
The size of the file in bytes.
Headers
The headers of the request.
str | None
The content type of the file from the request headers (e.g., “image/png”, “application/pdf”).

Methods

read

Read bytes from the file asynchronously.
int
default:"-1"
The number of bytes to read from the file. Default is -1, which reads the entire file.
Returns: The bytes read from the file.

write

Write bytes to the file asynchronously.
bytes
required
The bytes to write to the file.
Note: You normally wouldn’t use this method for files received in a request.

seek

Move to a specific position in the file.
int
required
The position in bytes to seek to in the file.
Any subsequent read or write will start from this position.

close

Close the file.
Always close files when you’re done to free up system resources.

Usage Notes

  • All methods are async-compatible and run in a threadpool
  • The file is automatically stored in memory up to a size limit, then spooled to disk
  • For small files, content is kept in memory for better performance
  • Use await file.read() to read the entire file contents
  • Remember to await file.close() or use context managers when appropriate

Learn More

Read more in the FastAPI docs for Request Files.