How to create a button(button) or a link(a) to download a particular file?

Asked

Viewed 29,719 times

4

I need to create a button that when clicking is performed the download and not open in another tab or window. Can be any type of file both image, pdf, music among others.

  • 3

    I’m using Ruby on Rails

  • 2

    There is a simple way, but for now only works in Chrome: <a href="url" download="nome-do-arquivo">Baixe!</a>. The guaranteed way is to force the download by the server.

  • @bfavaretto, you have some article something showing how to do this?

  • About the attribute: http://davidwalsh.name/download-attribute, https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a, http://caniuse.com/#feat=download. About forcing on the server, with ruby/Rails I do not know, but certainly has how to do.

  • Okay, thank you very much!

  • 1

    @Jeffersonalison: take a look here: https://www.google.se/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=ruby+on+Rails+download+site:stackoverflow.com

  • You can treat your file with a different controller if you don’t want to handle the HTTP server settings. For this you could use the send_file

  • Oops, thanks @Sergio! I’ll look there.

  • @Jeffersonalison if you find a good place here.

  • I’ve created an example that can help you https://answall.com/questions/74750/disponir-arquivo-para-download-via-javascript

Show 5 more comments

3 answers

2

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

Create a controller named 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 to 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: inserir a descrição da imagem aqui

0

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

<a href="/images/myw3schoolsimage.jpg" download>

inserir a descrição da imagem aquiinserir a descrição da imagem aqui

0

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

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

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

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

I hope I’ve helped

Browser other questions tagged

You are not signed in. Login or sign up in order to post.