from fastapi import FastAPI, File, UploadFile, HTTPException app = FastAPI() @app.post('/upload') async def upload_file(file: UploadFile = File(...)): contents = await file.read() if len(contents) > 1024 * 1024: raise HTTPException(status_code=400, detail='File too large') return {'filename': file.filename, 'size': len(contents)}
The code reads the entire file content and checks if its length exceeds 1MB (1024*1024 bytes). If it does, it raises an HTTPException with status 400 and a message 'File too large'. So uploading a 2MB file triggers this error.
from fastapi import FastAPI, File, UploadFile, HTTPException app = FastAPI() @app.post('/upload') async def upload_file(file: UploadFile = File(...)): if ???: raise HTTPException(status_code=400, detail='Only PNG files allowed') return {'filename': file.filename}
The correct MIME type for PNG images is 'image/png'. The code should check if file.content_type is not equal to this to raise an error. Option A does this correctly.
from fastapi import FastAPI, File, UploadFile, HTTPException app = FastAPI() @app.post('/upload') async def upload_file(file: UploadFile = File(...)): if file.spool_max_size < 1024 * 1024: raise HTTPException(status_code=400, detail='File too large') return {'filename': file.filename}
spool_max_size is a setting that controls the maximum size of file data kept in memory before spooling to disk. It is not the size of the uploaded file. To check file size, you must read the file contents and measure length.
from fastapi import FastAPI, File, UploadFile, HTTPException app = FastAPI() @app.post('/upload') async def upload_file(file: UploadFile = File(...)): if file.content_type != 'image/png': raise HTTPException(status_code=400, detail='Only PNG files allowed') contents = await file.read() return {'filename': file.filename, 'size': len(contents)}
The code checks if the uploaded file's content type is not 'image/png'. Since the file is JPEG, it raises an HTTPException with status 400 and the message 'Only PNG files allowed'.
Reading the entire file into memory means the server holds all bytes at once. For large files, this can cause high memory consumption and slow down the server or even crash it. A better approach is to limit upload size at the server or stream the file in chunks.