Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a file from rails application

I can't seem to find a simple and clear answer to this problem anywhere! Everything seems either outdated or incomplete!

I just want the user to be able to click on a link or button and download a file (that is somewhere in the public folder)

I tried this:

#view
<%= link_to "Raw blast output" ,:action => :download, :file_name => "public/data/02_blastout/#{@bl_file}" %>
#controller
def download
    send_file "#{RAILS_ROOT}/#{params[:file_name]}"
end

but I get this error:

No route matches {:action=>"download", :file_name=>"public/data/02_blastout/input0.fa_x_Glyma1aaunq.bl", :controller=>"cvits"}

Thanks for the help!!

like image 523
bdeonovic Avatar asked Jun 17 '11 21:06

bdeonovic


People also ask

How do I download a file in rails?

For Example: i Have my file in SVG folder inside Public Directory. Now we Can Access any file in Public Folder Like below and Pass id and Download option. Download option rename any file which u want to download. Now Click able link is Ready We Can Click on Above link to Download the File.

How to download a file in Ruby?

Plain old Ruby The most popular way to download a file without any dependencies is to use the standard library open-uri . open-uri extends Kernel#open so that it can open URIs as if they were files. We can use this to download an image and then save it as a file.

How do I read an image in Ruby?

You need to invoke mspaint.exe with the applicable command line flags. Do note though that I don't believe MSPaint handles JPG files. You'd need to search around google or perhaps submit another question regarding MSPaint and opening files via the command line.


1 Answers

Don't use send_file with a parameter set by a user. This opens up a massive security hole, allowing a user to access any file that is readable by your application (namely, your entire application, but also possibly other files on the filesystem).

Rather, if the file is under public, link to the file itself. In your case:

<%= link_to "Raw blast output", "/data/02_blastout/#{@bl_file}" %>

No need for a special controller action.

like image 132
Mario Avatar answered Oct 06 '22 01:10

Mario