如何创建下载链接

时间:2011-05-19 19:13:04

标签: ruby-on-rails ruby-on-rails-3

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

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

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

在控制器中:

def download
  send_file ...
end 

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

感谢。

3 个答案:

答案 0 :(得分:7)

我将下载操作添加为资源块中的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) %>

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

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

答案 1 :(得分:2)

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

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

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

答案 2 :(得分:1)

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

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

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

相关问题