2011-05-19 108 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> 

我發現這比其他任何解決方案都容易。