Setting up a link in your Rails app to allow your users to download any file is incredibly easy. Not just incredibly easy - OMGWTHBBQ easy! Stuff like this makes Rails so cool!

First, put the file out on your server. I put my "README.txt" file in a "files" folder like this: "rails/ appname/files/README.txt."

Next, set up a link in one of your pages:
1
2

<%= link_to 'Get Readme', :action => 'get_readme' %>
Finally, add the "get_readme" action method to your controller:
1
2
3
4

  def get_readme
    send_file("files/README.txt", :filename => 'yo_readme.txt')
  end
That's it! Now, whenever a user clicks the "Get Readme" link on your page, the file will be sent to the client. The :filename option simply allows you to suggest a name for the file to your users. I threw it in just to see how it works. I couldn't believe it was this easy, but sure enough, it is. Very cool.

There are other options like the :filename option which allow you to tell the browser what type of file to expect, how to display the file, and whether or not to stream the download. Streaming is turned on by default and allows downloading of very large files. All of these options go into the same line of code. Take a look at the article at this link.

As usual, expect a quick video demonstration of this posted later tonight.

5 Responses to “How to Send Files in Rails”

  1. peri Says:
    I have been looking up this very same thing myself (a bit of a supernoob, myself!). I am coming from an IIS background and curisous how to make sure someone cant just type in an URL to get to this file?
  2. TAD Says:
    I'm not sure peri. I'm guessing that this method doesn't obscure the URL so that someone can't just get it that way. There's probably some other way to do that.
  3. stephen Says:

    to answer your question about securing the file, you will need to install an authentication system like acts_as_authenticated, and protect the controller (or your entire application) with a login system. this is pretty straightforward to setup. you might be able to configure your webserver, i.e. apache, lighttpd, etc. to do the authentication but this is messy. hope that helps.

  4. kedar Says:

    can i do the two things at a time means i want to use send_file function and at the same time after download the file how should i redirect to some another page. and how should i know that the file is actually downloaded. could you tell me please

  5. osteonync Says:

    penetrations anal stokings fuck movie tenn porno , vagina anal objects porn. Free porn , anal extreme fist. Dildo inflate mpeg extreme anal , painful anal torture extreme hole mpg chicks, videoassexam. , holes violence sex videos ass pissing movies , http://extjs.com/forum/member.php?u=45321&nude-teens nude teens http://forums.seds.org/member.php?u=6292&anal-sex anal sex http://extjs.com/forum/member.php?u=45322&wet-pussy wet pussy http://forums.seds.org/member.php?u=6293&female-orgasm female orgasm

    s

Leave a Reply