tessad
tessad

Reputation: 1229

User click on image to download public file in rails

I'd like a user of my rails app to be able to click on a link 'download' and that they will then download a png file I have placed in my public folder. ('tool.png')

At the moment I have the incorrect...

<%= link_to "download", '/tool.png', :action => 'download' %>

I have created a download action in the controller:

def download
    send_file '/tool.png', :type=>"application/png", :x_sendfile=>true
end

What is happening here is that when a user clicks on the 'download' link it opens tool.png in its own window, rather than actually downloading the file.

Can anyone help me with this?

Thanks

Upvotes: 1

Views: 2184

Answers (2)

davegson
davegson

Reputation: 8331

HTML 5

For HTML5 it's actually very simple. You don't need a special controller action.

<%= link_to "download", '/tool.png', :download => 'filename' %>
# 'filename' specifies the new name for the downloaded file

Note: check the docs to see what browsers are supported

< HTML 5

If you want to support all browsers you must use the download action which you setup. The only thing missing is setting up the correct route.

routes.rb

get '/download_pdf', "controller_name#download", :as => :download_pdf

then link your HTML to the correct path, which will call the download action and send the file.

<%= link_to "download", :download_pdf_path

Upvotes: 7

maximus ツ
maximus ツ

Reputation: 8065

What you need is

<%= link_to "download", '/download', :action => 'download' %>

not

<%= link_to "download", '/tool.png', :action => 'download' %>

Where "/download" is the rails route which need to be specified in routing file.

since in your case your are not actually hitting the controller, you are just accessing http://host/tool.png. Check your development logs for more info, you will see no logs since request is not directly served by rails but with other case you will see them.

Upvotes: 1

Related Questions