0

In my Ruby on Rails 4 application I want to provide the user with a download for a png image.

Firstly, where would this png need to be placed:

  • /public
  • /assets/images

Secondly, how would I do that?
I've tried what the 2nd answer here says, and I am getting this error:
No route matches [GET] "/public/diagram.png"

The implementation of the above answer:
At my view:
<%= link_to "DOWNLOAD", "/public/diagram.png" %>

The controller:

class ControllerNamesController < ApplicationController 
// other actions defined: index, show, create, new, edit, update, destroy
def download_png
    send_file(
        "#{Rails.root}/public/diagram.png",
        filename: "diagram.png",
        type: "application/png"
    )
end

Τhe routes file (has all the controllers defined like this):

resources :ControllerName  
get "ControllerName/download_png", as: :download
Community
  • 1
  • 1
Chris
  • 3,619
  • 8
  • 44
  • 64
  • try to use path <%= link_to "DOWNLOAD", "/diagram.png" %> when your image is in public folder – Nitin Jain May 01 '14 at 17:48
  • @NitinJ: Great, this worked. But it loaded the image into the browser. How can I make it open a download dialog? – Chris May 01 '14 at 17:55

3 Answers3

2

Try using this

view

<%= link_to "Download" ,:action => :download %>

controller

def download
    send_file '/home/blog/downloads/away.png',:type=>"application/png", :x_sendfile=>true
end
Anshul Kalra
  • 198
  • 3
  • 13
0

For the question,putting the images in /public would be fine. And for the error which you are getting,this is the problem

You are just putting the path of the image file in the link_to helper while it expects a route.

Try changing it to

<%= link_to "DOWNLOAD", home_download_png_url %>

Edit

Can't think why it didn't worked.Okay,as @nithinJ suggested you can use

<%= link_to "DOWNLOAD", "/diagram.png" %>

And as you mentioned,you want it to be downloded rather than opening in the new brower,you could do this in the controller

send_file '#{Rails.root}/public/diagram.png', type: 'image/png', disposition: 'attachment'

For more info,see send_file.

Pavan
  • 33,316
  • 7
  • 50
  • 76
  • Adding this, yields this error: `undefined local variable or method `cr12s_download_png_url' for ..class` – Chris May 01 '14 at 17:49
  • Added the new send_file, but it still opened in the same tab. – Chris May 01 '14 at 18:19
  • Are you sure the controller is being called and the file isn't just being served by the server? What is the generated link? – Eyeslandic May 01 '14 at 20:17
0

do this in route.rb

get "home/download_png" , as: :download

in view, change this

<%= link_to "DOWNLOAD", download_path %>
Paritosh Piplewar
  • 7,982
  • 5
  • 26
  • 41