Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning files from rails

Beginner rails question: How does one return a file from a controller in rails?

I'm familiar with returning/rendering JSON objects. However I've never returned/rendered a file w/ an arbitrary extension.

From reading around SO it sounds like render :nothing => true could help. I'm just looking for some guidance or relevant documentation.

like image 525
SundayMonday Avatar asked Feb 10 '12 18:02

SundayMonday


1 Answers

You can use the built-in rails send_file or send_data method.

To stream a file (e.g. for a file proxy endpoint), use send_file:

send_file("#{RAILS_ROOT}/path/to/file/on/server",
  :filename => "client-suggested-filename",
  :type => "mime/type")

To stream generated data (e.g. for a generated pdf), use send_data:

send_data(your_data,
  :filename => "client-suggested-filename",
  :type => "mime/type")

The file extension and mime type don't have to match up, but they probably should just to conform to end user expectations. For example, if you are sending with a mime type of application/pdf, you should really set the :filename to something.pdf.

If you're not sure what the mime type is for the file you are sending, you can check this wikipedia page or use the mime-types gem. (Or if you are reading from a database that stores the mime type, use that).

like image 66
Ben Lee Avatar answered Oct 17 '22 11:10

Ben Lee