--- name: phoenix-uploads description: "Use when implementing file uploads or serving uploaded files — allow_upload, consume_uploaded_entries, content-type allowlists, validators, local vs S3/external storage, authorized downloads." --- # Phoenix File Uploads > Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2, Ecto 3.14 — October 2026 ## RULES — Follow these with no exceptions 1. **Never take the stored extension or the served content type from the client.** LiveView accepts an entry when its client MIME type **or** its file extension matches `:accept`, so `x.html` sent as `image/png` passes. Sniff the magic bytes of the uploaded file and pick the extension from an allowlist keyed on the detected type. 2. **Name files on the server** — `Ecto.UUID.generate() <> allowlisted_ext`. Never put `entry.client_name` (or any request param) in a path. 3. **Store under a configured directory, not a cwd-relative `"priv/static/uploads"`.** `priv/static` is replaced on every release deploy and runtime files are never in the digest manifest. Read the directory from app config at runtime and serve it with its own `Plug.Static` (or use object storage via `:external`). 4. **Private files go through a controller that loads the record through the scope** — `Media.get_document!(scope, id)`. Never accept a filename or path from the request. Send an allowlisted `content_type`, `disposition: :attachment` and `x-content-type-options: nosniff`. 5. **The `consume_uploaded_entries/3` callback must return `{:ok, value}` or `{:postpone, value}`.** Wrap the context result (`{:ok, Media.create_image(...)}`) and handle failures after consuming. 6. **Render `upload_errors/1` and `upload_errors/2`, and make `error_to_string/1` total** — atoms, `{:external_metadata_failure, _}`, `{:writer_failure, _}`, your `validator:` reasons, and a catch-all. 7. **Form markup is Phoenix 1.8:** assign `:form` in `mount`, give `<.form>` an `id`, put `<.button>` directly inside it (`<.form>` has no `actions` slot), and use a plain `