如何创建下载链接

创建下载链接的最佳方法是什么? 有没有比以下更好的方法?

我正在考虑在视图中使用link_to "Download", :controller => ..., :action => ...", :id => ...

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

在控制器中:

 def download send_file ... end 

此外,如果可能,我希望用户与链接保持在同一页面上。

谢谢。

我将下载操作添加为资源块中的restful路由。 这是我的典型代码:

的routes.rb

  resources :things do member do get :download end end 

模型:

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

控制器:

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

视图:

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

这使用户保持在同一页面上,并使用我建议的名称启动下载(我使用永久链接)。

动态生成是什么意思? 它们是由您上传还是由您的应用程序即时创建的?

您可以在show动作中使用下载逻辑并给它:

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

我很确定:controller /:action /:id链接方法是不受欢迎的。

我刚刚创建了一个Download .mp3链接,并在我的.htaccess文件中使用。

  ForceType application/octet-stream Header set Content-Disposition attachment  

我发现这比任何其他解决方案都容易。