2014-02-25 116 views
3

有人能告訴我如何用send_file下載文件?如何使用send_file下載文件?

我有一個文件image.jpg裏面app/assets/images。我在我的控制器嘗試這樣:

def download 
    send_file ("#{Rails.root}/public/images/image.jpg") 
end 

def download 
    send_file ("#{Rails.root}/assets/images/image.jpg") 
end 

def download 
    send_file ("#{Rails.root}/images/image.jpg") 
end 

def download 
    send_file ("/public/images/image.jpg") 
end 

def download 
    send_file ("/assets/public/images/image.jpg") 
end 

def download 
    send_file ("/assets/images/image.jpg") 
end 

對於每條路徑,它說:

ActionController::MissingFile in HomeController#download 
Cannot read file 'some_path' 

什麼可以在這裏是一個問題?謝謝!

回答

8

嘗試:

IMAGES_PATH = File.join(Rails.root, "public", "images") 

def download 
    send_file(File.join(IMAGES_PATH, "image.jpg")) 
end 
+0

謝謝你的建議,但它是一樣的。找不到文件。 – user3339562

+0

即使在/ public/images目錄中存在image.jpg文件,也會出現此錯誤?也許嘗試重新啓動你的應用服務器。這應該肯定會起作用。 – Coenwulf

2

好,我建議你到你的文件移動到公用文件夾。無論如何,這樣做

send_file(Rails.root.join('app' , 'assets', 'images', 'image.jpg')) 
2

我們需要指定礦的類型,以便它會緩存。

send_file ("#{Rails.root}/public"+image.image_path), :type => "image/jpeg", :disposition => 'inline' 
3
In your view => 
<%= link_to "click here to download", signed_feeds_pdf_path(:feed_image_path => feed_image.feedimage.path), target: '_self' %> 

In your controller => 
    def pdf 
    file_name = params[:feed_image_path].split('/').last 
    @filename ="#{Rails.root}/public/uploads/feed_image/feedimage/#{file_name}" 
    send_file(@filename , 
     :type => 'application/pdf/docx/html/htm/doc', 
     :disposition => 'attachment')   
    end 
soo simple...... 
1

對於任何人仍然在尋找一個答案,SEND_DATA和由send_file響應AJAX調用時將無法正常工作。請嘗試提交表單或使用<a href=..>調用控制器方法並下載文件。

相關問題