How to Create Download Link

为君一笑 提交于 2019-12-31 22:37:13

问题


What's the best way to create a download link? Is there a better way than the following?

I was thinking of using link_to "Download", :controller => ..., :action => ...", :id => ... in the view.

Adding match /documents/download/:id => documents#download to routes.rb

And in the controller:

def download
  send_file ...
end 

Also, I'd like, if possible, for the user to remain on the same page as the link.

Thanks.


回答1:


I add the download action as a restful route in a resources block. Here's typical code for me:

routes.rb

  resources :things do
    member do
      get :download
    end
  end    

model:

  has_attached_file :document,
    :path => ':rails_root/assets/documents/:id/:basename.:extension'
  attr_protected :document_file_name, :document_content_type, :document_file_size

controller:

  def download
    send_file @thing.document.path, :type => 'application/pdf', :filename => @thing.permalink
  end

view:

  <%= link_to 'Download', download_thing_path(@thing) %>

This keeps the user on the same page, and just initiates the download with my suggested name (I use permalink).

What do you mean by dynamically generated? Are they uploaded by you or created by your application on the fly?




回答2:


You could just have your download logic in your show action and give it:

<%= link_to "Download", document_path(document) %>

I'm pretty sure that the :controller / :action / :id method of linking is frowned upon.




回答3:


I've just created a Download .mp3 link and used in my .htaccess file.

<Files *.mp3>
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</Files>

I found this to be easier than any other solution.



来源:https://stackoverflow.com/questions/6063721/how-to-create-download-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!