The UploadFile class provides an interface for handling file uploads in FastrAPI applications.
Overview
UploadFile is automatically provided when you use the File() parameter with type annotation. It provides async methods for reading and manipulating uploaded files.
Properties
The name of the uploaded file
The MIME type of the uploaded file (e.g., “image/png”, “application/pdf”)
The size of the file in bytes
Methods
read()
Read the contents of the uploaded file.
async def read ( size : int = - 1 ) -> bytes
Number of bytes to read. Use -1 to read the entire file.
Returns the file contents as bytes.
write()
Write data to the file.
async def write ( data : bytes ) -> None
Data to write to the file
seek()
Move the file cursor to a specific position.
async def seek ( offset : int ) -> None
Position to seek to (0-based)
close()
Close the file.
async def close () -> None
Examples
Basic file upload
from fastrapi import FastrAPI, File, UploadFile
app = FastrAPI()
@app.post ( "/upload" )
async def upload_file ( file : UploadFile = File( ... )):
contents = await file .read()
return {
"filename" : file .filename,
"content_type" : file .content_type,
"size" : len (contents)
}
Multiple file uploads
from fastrapi import FastrAPI, File, UploadFile
app = FastrAPI()
@app.post ( "/upload-multiple" )
async def upload_multiple_files ( files : list[UploadFile] = File( ... )):
file_info = []
for file in files:
contents = await file .read()
file_info.append({
"filename" : file .filename,
"content_type" : file .content_type,
"size" : len (contents)
})
return { "files" : file_info}
Save uploaded file
from fastrapi import FastrAPI, File, UploadFile
import aiofiles
app = FastrAPI()
@app.post ( "/upload-save" )
async def upload_and_save ( file : UploadFile = File( ... )):
# Read file contents
contents = await file .read()
# Save to disk
file_path = f "uploads/ { file .filename } "
async with aiofiles.open(file_path, "wb" ) as f:
await f.write(contents)
return {
"filename" : file .filename,
"saved_to" : file_path,
"size" : len (contents)
}
from fastrapi import FastrAPI, File, Form, UploadFile
app = FastrAPI()
@app.post ( "/upload-with-metadata" )
async def upload_with_metadata (
file : UploadFile = File( ... ),
description : str = Form( ... ),
category : str = Form( ... )
):
contents = await file .read()
return {
"filename" : file .filename,
"size" : len (contents),
"description" : description,
"category" : category
}
Validate file type
from fastrapi import FastrAPI, File, UploadFile, HTTPException
app = FastrAPI()
ALLOWED_TYPES = [ "image/jpeg" , "image/png" , "image/gif" ]
@app.post ( "/upload-image" )
async def upload_image ( file : UploadFile = File( ... )):
if file .content_type not in ALLOWED_TYPES :
raise HTTPException(
status_code = 400 ,
detail = f "Invalid file type. Allowed types: { ', ' .join( ALLOWED_TYPES ) } "
)
contents = await file .read()
return {
"filename" : file .filename,
"content_type" : file .content_type,
"size" : len (contents)
}
Stream large file
from fastrapi import FastrAPI, File, UploadFile
app = FastrAPI()
@app.post ( "/upload-large" )
async def upload_large_file ( file : UploadFile = File( ... )):
# Process file in chunks to handle large files
chunk_size = 1024 * 1024 # 1MB chunks
total_size = 0
while True :
chunk = await file .read(chunk_size)
if not chunk:
break
total_size += len (chunk)
# Process chunk here
return {
"filename" : file .filename,
"total_size" : total_size
}
Implementation details
FastrAPI’s UploadFile is implemented in Rust (src/datastructures.rs:4-67) for performance. It provides:
Async I/O : All file operations are asynchronous
Memory efficiency : Files are stored in memory with efficient buffering
Thread-safe : Safe to use across async tasks
Standard interface : Compatible with FastAPI’s UploadFile API
Best practices
Always use await when calling UploadFile methods, as they are asynchronous.
Files are stored in memory. For very large files, consider streaming to disk or using chunked reading to avoid memory issues.
Validate file types and sizes before processing to prevent security issues and resource exhaustion.
Parameters Parameter extraction classes
Form data Working with form data
Error handling Handle upload errors
Request handling Understand request processing