Trung BìnhFastAPI iconFastAPI

File upload trong FastAPI nên dùng `bytes` hay `UploadFile`?

bytes đọc toàn bộ file vào memory, chỉ phù hợp file nhỏ. UploadFile dùng spooled file, có metadata như filename/content_type và hỗ trợ async read, phù hợp file lớn hơn.

Ví dụ:

python
@app.post("/avatar")
async def upload_avatar(file: UploadFile):
    content_type = file.content_type
    data = await file.read()

Production cần giới hạn size, validate content type thật, scan nếu cần, lưu object storage và tránh tin filename từ client.

Xem toàn bộ FastAPI cùng filter theo level & chủ đề con.

Mở danh sách FastAPI