2011-05-19 111 views
10

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

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

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

和Controller:

def download 
    send_file ... 
end 

而且,我想,如果可能的话,为用户保持在同一页面的链接。

谢谢。

+0

您发送的文件非常大或动态生成吗? – dwhalen 2011-05-19 19:22:01

+0

@Danny Rockets:是的,这些文件是动态生成的。 – tendans6 2011-05-19 19:26:13

+0

http://stackoverflow.com/questions/6392003/how-to-download-a-file-from-rails-application – sybind 2013-08-31 06:01:50

回答

7

我在资源块中添加下载操作作为一个安静的路线。下面是典型的代码对我来说:

的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) %> 

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

你是什么意思动态生成?他们是由您上传还是由您的应用程序在飞行中创建?

+0

我将问题理解为意味着不像静态可用的任何内容,例如预加载的图标图像或许可证文本文件。在我的情况下(文本,文档,pdf)文件由一组用户生成和上传;动态方面来自上传的特殊性质。 – tendans6 2011-05-19 23:32:57

+1

如果我正确地理解了你,那么在我的示例中,下载操作中的your:type可以是@ thing.document_content_type,而不是'application/pdf'。 – Preacher 2011-05-20 02:21:23

2

你可能只是有你的下载逻辑在你的表演动作,并给它:

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

我敢肯定的是:控制器/:动作/:链接的ID方法皱眉。

+1

ammend路线是:match/documents/download /:id => documents#download:as =>:文档 – brycemcd 2011-05-19 19:35:41

1

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

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

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