UploadFile
A file uploaded in a request. Define it as a path operation function parameter or dependency to receive uploaded files. For regulardef 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.
write
Write bytes to the file asynchronously.bytes
required
The bytes to write to the file.
seek
Move to a specific position in the file.int
required
The position in bytes to seek to in the file.
close
Close the file.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