How to Make Rails Endpoint Return Downloadable File

Suppose you want an endpoint that returns a file that the browser would open a “file download” dialogue. You can do so by setting the Content-Disposition.

Example:

class FooController < ApplicationController
  def show
    response.headers["Content-Disposition"] = "attachment; filename=foo.txt"
    render plain: "foobar"
  end
end

In the example, when hitting the show path, most browsers will pop open a download box asking to save "foo.txt". Note, that you need to pass in "Content-Disposition" (string) and not :content_disposition (symbol).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: