{"id":"43c4dabe9d7439ae","repo":"pallets/flask","slug":"you-tried-to-access-the-file-key-r-in-the-reques","errorCode":null,"errorMessage":"You tried to access the file {key!r} in the request.files dictionary but it does not exist. The mimetype for the request is {request.mimetype!r} instead of 'multipart/form-data' which means that no file contents were transmitted. To fix this error you should provide enctype=\"multipart/form-data\" in your form.\n\nThe browser instead transmitted some file names. This was submitted: {names}","messagePattern":"You tried to access the file (.+?) in the request\\.files dictionary but it does not exist\\. The mimetype for the request is (.+?) instead of 'multipart/form-data' which means that no file contents were transmitted\\. To fix this error you should provide enctype=\"multipart/form-data\" in your form\\.\n\nThe browser instead transmitted some file names\\. This was submitted: (.+?)","errorType":"exception","errorClass":"DebugFilesKeyError","httpStatus":400,"severity":"error","filePath":"src/flask/debughelpers.py","lineNumber":98,"sourceCode":"\ndef attach_enctype_error_multidict(request: Request) -> None:\n    \"\"\"Patch ``request.files.__getitem__`` to raise a descriptive error\n    about ``enctype=multipart/form-data``.\n\n    :param request: The request to patch.\n    :meta private:\n    \"\"\"\n    oldcls = request.files.__class__\n\n    class newcls(oldcls):  # type: ignore[valid-type, misc]\n        def __getitem__(self, key: str) -> t.Any:\n            try:\n                return super().__getitem__(key)\n            except KeyError as e:\n                if key not in request.form:\n                    raise\n\n                raise DebugFilesKeyError(request, key).with_traceback(\n                    e.__traceback__\n                ) from None\n\n    newcls.__name__ = oldcls.__name__\n    newcls.__module__ = oldcls.__module__\n    request.files.__class__ = newcls\n\n\ndef _dump_loader_info(loader: BaseLoader) -> t.Iterator[str]:\n    yield f\"class: {type(loader).__module__}.{type(loader).__name__}\"\n    for key, value in sorted(loader.__dict__.items()):\n        if key.startswith(\"_\"):\n            continue\n        if isinstance(value, (tuple, list)):\n            if not all(isinstance(x, str) for x in value):\n                continue\n            yield f\"{key}:\"\n            for item in value:","sourceCodeStart":80,"sourceCodeEnd":116,"githubUrl":"https://github.com/pallets/flask/blob/6a2f545bfd8ed31e19066a299296917e034aca58/src/flask/debughelpers.py#L80-L116","documentation":"This is `DebugFilesKeyError`, raised in debug mode when your view accesses `request.files['key']` but the request was not sent as `multipart/form-data`. Flask (via `Request._load_form_data` in wrappers.py) patches the files multidict's `__getitem__` (`attach_enctype_error_multidict` in debughelpers.py) so that, when the key is missing from `files` but present in `form`, you get this explanatory error instead of a bare KeyError — the browser sent only the file *names* as text fields because the form lacked the right enctype.","triggerScenarios":"A view does `request.files['upload']` on a POST from an HTML `<form>` without `enctype=\"multipart/form-data\"`; the field name appears in `request.form` (as the filename string) but not in `request.files`, `app.debug` is True, and the request mimetype is `application/x-www-form-urlencoded`.","commonSituations":"Forgetting the enctype attribute on upload forms; sending uploads from JS/fetch or requests with default urlencoded/JSON encoding instead of FormData/multipart; API clients posting `files` under `data=` in Python `requests`.","solutions":["Add `enctype=\"multipart/form-data\"` to the HTML form (and use `method=\"post\"`).","If uploading via JavaScript, send a `FormData` object without manually setting Content-Type so the browser sets the multipart boundary.","If using Python `requests`, pass the file via `files={'upload': fh}` rather than `data=`.","In production-safe code, use `request.files.get('upload')` and handle the missing case explicitly."],"exampleFix":"<!-- before -->\n<form method=\"post\">\n  <input type=\"file\" name=\"upload\">\n</form>\n<!-- after -->\n<form method=\"post\" enctype=\"multipart/form-data\">\n  <input type=\"file\" name=\"upload\">\n</form>","handlingStrategy":"validation","validationCode":"# check before accessing request.files\nif request.mimetype != 'multipart/form-data' or key not in request.files:\n    abort(400, 'file upload missing or form lacked enctype=multipart/form-data')","typeGuard":"def has_uploaded_file(request, key: str) -> bool:\n    return request.mimetype == 'multipart/form-data' and key in request.files","tryCatchPattern":null,"preventionTips":["Always set enctype=\"multipart/form-data\" on HTML forms containing <input type=file>","In tests, pass data={'file': (io.BytesIO(b'..'), 'name.txt')} with content_type='multipart/form-data'","Use request.files.get(key) and handle None instead of indexing directly","Validate request.mimetype at the top of upload views and return a clear 400"],"tags":["flask","file-upload","forms","multipart","debug-mode"],"analyzedSha":"6a2f545bfd8ed31e19066a299296917e034aca58","analyzedAt":"2026-07-31T19:13:49.921Z","schemaVersion":2}