How do I create a button or a link to download a specific file?

4

I need to create a button that when clicked is downloaded and not opened in another tab or window. It can be any type of file both image, pdf, music among others.

    
asked by anonymous 15.08.2014 / 21:02

4 answers

2

I have determined a method that will get the download parameter of a link_to() , so that it would serve several types. To follow this example I have a file called: javascript_the_good_parts.pdf located in / public / .

Create a controller called Pages (app / controllers / pages_controller.rb):

class PagesController < ApplicationController
  def index    
  end
  def download
    send_file "#{Rails.root}/public/#{params[:file_name]}"
  end
end

Add in your routes (config / routes.rb):

root 'pages#index'
get 'download'=> 'pages#download'

And as page (app / views / pages / index.html):

<%= link_to "Fazer Dowload" ,:action => :download, :file_name => "javascript_the_good_parts.pdf" %>

Screenshot Example:

    
19.08.2014 / 19:19
0

You can treat your file with a different driver if you do not want to handle the HTTP server settings.

For this you could use send_file

    
15.08.2014 / 21:22
0

There is the download attribute in HTML5 that can be used like this:

<a href="/images/myw3schoolsimage.jpg" download>
    
19.08.2014 / 17:29
0

First you have to put a iframe hidden and without src in your application

<iframe name="iframe_download" class="hidden"></iframe>

Now you can put the download link with the target to the hidden iframe

<a href="/caminho/para/download.pdf" target="iframe_download">Clique para baixar</a>

I hope I have helped

    
20.08.2014 / 00:57