Performance: File upload (single file)
This affects the page load speed and interaction responsiveness when uploading a single file through the frontend to the backend.
Jump into concepts and practice - no test required
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post('/upload') async def upload_file(file: UploadFile = File(...)): contents = await file.read() return {'file_size': len(contents)}
from fastapi import FastAPI, File app = FastAPI() @app.post('/upload') async def upload_file(file: bytes = File(...)): # process file bytes directly return {'file_size': len(file)}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Reading file as bytes (File(...)) | Minimal | 0 | 0 | [X] Bad |
| Using UploadFile with async read | Minimal | 0 | 0 | [OK] Good |
UploadFile to handle file uploads efficiently.UploadFile, not a list or primitive type.File(...) to mark the parameter as a file upload.UploadFile combined with File(...) for single file upload.from fastapi import FastAPI, UploadFile, File
app = FastAPI()
@app.post('/upload')
async def upload(file: UploadFile = File(...)):
content = await file.read()
return {'filename': file.filename, 'content_type': file.content_type, 'size': len(content)}await file.read() to get the file bytes, so content length is 5 for 'hello'.from fastapi import FastAPI, UploadFile
app = FastAPI()
@app.post('/upload')
def upload(file: UploadFile = File(...)):
content = file.read()
return {'filename': file.filename, 'size': len(content)}File and the function is not async but calls file.read() which is async.await file.read().file: UploadFile = File(...).await file.read(), then slice first 10 bytes and decode to UTF-8 string.