In a Rails controller, when do you use send_file versus send_data, and what do their disposition:, type: and filename: options control?
answer
- a path on disk vs bytes in memory
- disposition defaults to attachment
- type guessed from filename's extension
- application/octet-stream as the fallback
- ActionController::MissingFile for an unreadable path
basics
~20 ssend_file serves a file that already exists on disk by its path; send_data sends a String of bytes built in memory. Both default to an attachment download, guess the type from filename's extension and fall back to application/octet-stream.
solid answer
~40 sI use `send_file` when the bytes are already on disk, such as an archived payslip PDF, and `send_data` when I generated them in memory, such as a payslip a PDF library just rendered. Both set the download headers: `disposition:` is `"attachment"` by default or `"inline"` to show it in the browser; `type:` takes a string or a Mime symbol like `:pdf` and, when omitted, is looked up from the extension of `filename:`, falling back to `application/octet-stream`; `filename:` is the suggested name in `Content-Disposition`. `send_file` defaults the filename to the path's basename and raises `ActionController::MissingFile` when the path is not a readable file; `send_data` has no default name. Both take `status:`, default 200. And `send_file` must never receive a path taken from params.
code
ruby · 15 linesclass PayslipsController < ApplicationController
def show
payslip = Current.user.payslips.find(params[:id])
name = "payslip-#{payslip.period}.pdf"
if payslip.archived?
# bytes already on disk: hand Rails the path
send_file payslip.archive_path, filename: name
else
# bytes rendered just now: hand Rails the String
pdf = PayslipPdf.new(payslip).render
send_data pdf, filename: name, type: :pdf, disposition: "inline"
end
end
endgo deeper
Recall the split: send_file takes a path to a file on disk, send_data takes a String you built. Know that attachment is the default disposition and that filename: sets the download name.
Explain how the type is chosen from filename's extension with an octet-stream fallback, why send_data with no filename stays octet-stream, and that a bad path raises MissingFile and ends as a 500.
Show the security reflex: never let params pick the path, scope the lookup to the user. Note that send_file's to_path body is what lets a front server deliver the file, while send_data holds it all in memory.
Frame the choice as where the bytes live and who should push them: stored files belong with storage or a front server, generated ones with send_data or a streamed export when they grow large.
## Two methods, two sources of bytes Every Rails controller includes `ActionController::DataStreaming`, which adds two private helpers for responses that are a file rather than a page: - **`send_file(path, options)`** serves bytes that already live **on disk**. You hand Rails a filesystem path; it checks that the path is a readable file, sets the download headers and makes the response body *point at* the file instead of loading it into a String. - **`send_data(data, options)`** serves bytes that live in a **Ruby String** you just produced: a PDF a library rendered, a ZIP assembled in memory, a CSV built from rows. Rails sets the same download headers and renders the string as the body (internally a `render body:` with those headers). In a payroll app the split is natural. Payslips from earlier periods sit in an archive folder and go out with `send_file`; the current period's payslip is rendered on request and goes out with `send_data`. ## The options both methods share | option | what it sets | default | |---|---|---| | `disposition:` | `Content-Disposition`: `"attachment"` (save dialog) or `"inline"` (the browser displays it) | `"attachment"` | | `type:` | `Content-Type`: a string such as `"application/pdf"` or a registered Mime symbol such as `:pdf` | guessed from `filename:`'s extension, else `application/octet-stream` | | `filename:` | the suggested name inside `Content-Disposition` | `send_file`: `File.basename(path)`; `send_data`: none | | `status:` | the HTTP status | `200` | Two details trip people up. - **The type guess reads the filename, not the file.** Rails calls `Mime::Type.lookup_by_extension` on the extension of `filename:`; it never sniffs the bytes. For `send_file` the filename defaults to the path's basename, so `42.pdf` becomes `application/pdf` with no extra option. For `send_data` without `filename:` there is nothing to guess from, so the type stays `application/octet-stream` unless you pass `type:`. - **The filename is written twice.** `ActionDispatch::Http::ContentDisposition` emits an ASCII-escaped `filename="..."` and an RFC 5987 `filename*=UTF-8''...`, so a payslip named after an employee with a non-ASCII surname still downloads under the right name. `send_file` also takes `url_based_filename: true`, which leaves the filename out so the browser picks one from the URL; an explicit `filename:` overrides it. ## What send_file does underneath 1. It raises **`ActionController::MissingFile`** unless `File.file?(path) && File.readable?(path)`. That class is not in the default `rescue_responses` map, so if nothing rescues it the visitor gets a **500**, not a 404. 2. It fills in `filename:` from the path, sets `Content-Type`, `Content-Disposition` and `Content-Transfer-Encoding: binary`, and sets the status. 3. It hands the response a body object that responds to **`to_path`**. That is what lets a front server deliver the file when `config.action_dispatch.x_sendfile_header` is configured; without it, Rails reads the file in chunks as the response is written instead of loading it whole. ## send_data holds everything in memory `send_data` renders a String, so the whole payload exists in memory before the first byte leaves, and the action can render only once. For a payslip of a few hundred kilobytes that is fine. For an export that runs to hundreds of megabytes and is produced row by row, `send_stream` from `ActionController::Live` writes as it goes instead. ## The security rule The method's own documentation warns that `send_file(params[:path])` lets a visitor download any file the Rails process can read. Look the record up through the signed-in user's scope, for example `Current.user.payslips.find(params[:id])`, and build the path on the server from data the user cannot choose. ## Choosing in practice | situation | call | |---|---| | the file already sits on local disk (an archive, an upload you stored yourself) | `send_file` | | a library returns the bytes as a String (a PDF renderer, a ZIP built in memory) | `send_data` | | the payload is large and produced row by row | `send_stream` in an `ActionController::Live` controller | | the file lives in Active Storage | the Active Storage controllers and URLs, not these helpers | Both helpers end the action's rendering: once one of them has run, the response is decided, exactly as if the action had called `render`. Authorization therefore has to happen before them, usually in a `before_action` or in the scoped lookup at the top of the action. ## Common mistakes - Passing a path string to `send_data`: the response body becomes the text of the path. - Passing PDF bytes to `send_file`: it treats them as a path and fails instead of sending anything. - Using `render plain:` for a binary file: it labels the body `text/plain` and adds no `Content-Disposition`. - Expecting a PDF to open in a browser tab without `disposition: "inline"`.
- What headers does send_data(pdf) produce when you pass neither type: nor filename:?`Content-Type: application/octet-stream` and a bare `Content-Disposition: attachment` with no filename. Without `filename:` there is no extension to look up, so Rails cannot guess `application/pdf`; the browser downloads the file and has to choose a name itself. Pass `filename:` (and `type: :pdf` if the name might lack an extension).
- Why is send_file(params[:path]) dangerous, and what do you do instead?The path is read straight from disk, so a crafted value can download any file the Rails process can read: logs, configuration, other users' documents. The method's own documentation warns about it. Look the record up through the signed-in user's scope and build the path on the server from stored data the user cannot choose.
- Can send_file answer with a status other than 200?Yes. Both `send_file` and `send_data` take `status:`, default 200. The Rails documentation's own example serves a static `404.html` with `type: "text/html; charset=utf-8"`, `disposition: "inline"` and `status: 404`.
- send_data reads the file at the path you give it, just like send_file.
- send_file defaults to disposition inline, so PDFs open in the browser tab.
- Without type:, Rails sniffs the file's bytes to choose the Content-Type.
- A missing file makes send_file answer 404 on its own.
- send_file(params[:path]) is safe because Rails limits it to the public folder.
- render plain: pdf is the same as send_data with a filename.