File() for small files and UploadFile for larger files with better memory management.
Installing Dependencies
File upload handling requires thepython-multipart package:
Upload File as Bytes
For small files, you can receive them asbytes:
The entire file content is stored in memory as
bytes. This is fine for small files but not recommended for large uploads.Upload File with UploadFile
UploadFile provides better performance and more features:
UploadFile Advantages
1
Memory Efficient
Files are spooled to disk after exceeding a size limit, saving RAM
2
Metadata Access
Access filename, content type, and other file metadata
3
Async Read/Write
Built-in async methods for reading file content
4
File-like Interface
Works like a Python file object
UploadFile Attributes and Methods
Available Methods
await file.read(): Read entire file contentawait file.read(size): Read up tosizebytesawait file.seek(position): Move to a specific positionawait file.write(data): Write data to fileawait file.close(): Close the file
Multiple File Uploads
Handle multiple files using lists:Optional File Upload
Make file uploads optional:File Upload with Additional Metadata
Combine file uploads with form data:When mixing
File() and Form(), the request must use multipart/form-data encoding.Processing Uploaded Files
Save to Disk
Stream Large Files
Validate File Type
File Size Limits
WhileUploadFile doesn’t have built-in size limits, you can implement them:
File() Parameters
TheFile() function supports validation and documentation:
Testing File Uploads
Key Differences: File vs UploadFile
Related Topics
- Request Forms - Handle form data with files
- Request Body - Work with JSON request bodies
- Response Model - Define response schemas