Chris
Chris

Reputation: 3698

How to create a download button (link) for a local image (png)

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:

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

Upvotes: 0

Views: 5053

Answers (3)

Anshul Kalra
Anshul Kalra

Reputation: 198

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

Upvotes: 2

Pavan
Pavan

Reputation: 33542

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.

Upvotes: 0

Paritosh Piplewar
Paritosh Piplewar

Reputation: 8132

do this in route.rb

get "home/download_png" , as: :download

in view, change this

<%= link_to "DOWNLOAD", download_path %>

Upvotes: 0

Related Questions