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.
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.
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:
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
There is the download
attribute in HTML5 that can be used like this:
<a href="/images/myw3schoolsimage.jpg" download>
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