We check files to make sure they are safe and the right kind before saving or using them.
File validation (size, type) in FastAPI
from fastapi import FastAPI, File, UploadFile, HTTPException from fastapi.responses import JSONResponse app = FastAPI() @app.post("/upload/") async def upload_file(file: UploadFile = File(...)): # Check file size and type here pass
Use UploadFile to handle uploaded files efficiently.
File size must be checked by reading the file content or using headers.
from fastapi import FastAPI, File, UploadFile, HTTPException app = FastAPI() @app.post("/upload/") async def upload_file(file: UploadFile = File(...)): if file.content_type not in ["image/jpeg", "image/png"]: raise HTTPException(status_code=400, detail="Only JPEG or PNG files allowed") contents = await file.read() if len(contents) > 2_000_000: raise HTTPException(status_code=400, detail="File too large") return {"filename": file.filename, "size": len(contents)}
from fastapi import FastAPI, File, UploadFile, HTTPException app = FastAPI() @app.post("/upload/") async def upload_file(file: UploadFile = File(...)): allowed_types = ["application/pdf"] if file.content_type not in allowed_types: raise HTTPException(status_code=400, detail="Only PDF files allowed") contents = await file.read() max_size = 5_000_000 # 5MB if len(contents) > max_size: raise HTTPException(status_code=400, detail="File too large") return {"filename": file.filename, "size": len(contents)}
This FastAPI app has one endpoint /upload/. It accepts a file upload, checks if the file is a JPEG or PNG, and ensures it is smaller than 2MB. If checks fail, it sends an error. Otherwise, it returns the file name and size.
from fastapi import FastAPI, File, UploadFile, HTTPException from fastapi.responses import JSONResponse app = FastAPI() @app.post("/upload/") async def upload_file(file: UploadFile = File(...)): allowed_types = ["image/jpeg", "image/png"] max_size = 2_000_000 # 2MB if file.content_type not in allowed_types: raise HTTPException(status_code=400, detail="Only JPEG or PNG files allowed") contents = await file.read() if len(contents) > max_size: raise HTTPException(status_code=400, detail="File too large") return JSONResponse(content={"filename": file.filename, "size": len(contents)})
Always check file.content_type to verify file type before reading content.
Reading the whole file with await file.read() lets you check size but can use memory for big files.
For very large files, consider streaming or chunk reading to avoid memory issues.
File validation helps keep uploads safe and within limits.
Check both file type and size before accepting files.
FastAPI's UploadFile makes it easy to handle uploaded files asynchronously.