Skip to main content
FastAPI makes it easy to handle file uploads using File() for small files and UploadFile for larger files with better memory management.

Installing Dependencies

File upload handling requires the python-multipart package:
Without python-multipart, file uploads won’t work and you’ll get an error at startup.

Upload File as Bytes

For small files, you can receive them as bytes:
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 content
  • await file.read(size): Read up to size bytes
  • await file.seek(position): Move to a specific position
  • await file.write(data): Write data to file
  • await file.close(): Close the file
Always use await when calling these methods since they’re asynchronous.

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

Always validate file types and sizes on the server side. Never trust client-provided MIME types alone.

File Size Limits

While UploadFile doesn’t have built-in size limits, you can implement them:

File() Parameters

The File() function supports validation and documentation:

Testing File Uploads

Key Differences: File vs UploadFile

Use UploadFile by default unless you have a specific reason to use bytes.