python config_error ai_generated true

fastapi.exceptions.HTTPException: 413 Request Entity Too Large

ID: python/fastapi-upload-file-size-limit

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2025-01-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9 active
3.10 active

Root Cause

上传的文件大小超过了 FastAPI 或服务器的限制

generic

中文

上传的文件大小超过了 FastAPI 或服务器的限制

Workarounds

  1. 90% success 使用 UploadFile 并设置最大大小
    from fastapi import UploadFile, File
    app = FastAPI()
    @app.post('/upload')
    async def upload(file: UploadFile = File(...)):
        if file.size > 10 * 1024 * 1024:
            raise HTTPException(413, '文件太大')
  2. 95% success 配置服务器限制
    uvicorn.run(app, limit_max_request_body=10*1024*1024)

Dead Ends

Common approaches that don't work:

  1. 在前端压缩文件但后端限制未改 60% fail

    压缩后仍可能超过限制,且质量下降

  2. 忽略错误并重试上传 90% fail

    每次都会失败,浪费带宽