InterviewHubPRO
Section Overview
Q55

Question 55 of 65

Part 4: Web Frameworks, APIs & FastAPI (41 - 55)

85%
Python & FastAPI•Part 4: Web Frameworks, APIs & FastAPI (41 - 55)

Secure File Uploads: `UploadFile` vs `bytes`:

In Simple Words:

  • bytes: Reads the entire file directly into RAM (crashes server on large multi-gigabyte files).
  • UploadFile: Uses a SpooledTemporaryFile; buffers in RAM up to 1MB, then rolls over to disk automatically.
python
from fastapi import UploadFile, File

@app.post("/upload")
async def upload_document(file: UploadFile = File(...)):
    # Stream chunks safely without loading entire file into RAM:
    while chunk := await file.read(1024 * 1024): # 1MB chunks
        pass
    return {"filename": file.filename}