2014-02-26 32 views
1

我需要一個快速提示,看起來很簡單。我有一些私人文件夾內的圖片,並希望在我的視圖中顯示它們。如何從視圖內的私人文件夾中顯示圖像?

我發現的唯一的解決辦法是這樣的:

def show 
    send_file 'some/image/url', :disposition => 'inline', :type => 'image/jpg', :x_sendfile => true 
end 

我讀過:disposition => 'inline'不應觸發圖像下載,讓我來顯示它在我的視圖中。問題是,每次我觸發show操作時,圖像下載都會自動激活並自動下載。不顯示show操作的視圖。

如何在View中顯示該圖像?謝謝。

回答

1

我這樣做的方式,我不是說這本書很完美,我是在圖像和動作控制器中渲染它。

所以,舉例來說,在routes.rb中

match '/images/:image', to: "your_controller#showpic", via: "get", as: :renderpic 

在你的控制器:

def showpic 
    send_file "some/path/#{params[:image]}.jpg", :disposition => 'inline', 
       :type => 'image/jpg', :x_sendfile => true # .jpg will pass as format 
end 

def show 
end 

而且在你看來

<img src="<%= renderpic_path(your image) %>"> 

這裏是一個工作例子,用較少的參數「send_file」

def showpic 
    photopath = "images/users/#{params[:image]}.jpg" 
    send_file "#{photopath}", :disposition => 'inline' 
end 
+0

我有一個'send_file'some/path /#{params [:image]}。jpg「,:disposition =>'inline'的方法, :type =>'image/jpg',:x_sendfile = > true'不通過。 Ma圖像源始終設置在'/ images /:image'上,而不是在我爲'send_file'指定的路徑上。所以它在'show.html.erb'視圖的url上設置。 – user3339562

+0

我會爲你加入一個工作示例。看我的編輯。 –

+0

您應該調用renderpic_path(「filename.jpg」)或「/images/filename.jpg」以使其工作。 –

1

我認爲這個問題是type。從技術文檔:

:type - specifies an HTTP content type 

所以正確的HTTP內容類型應該是image/jpeg而不是image/jpg,因爲你可以see here。試着用:

:type => 'image/jpeg'

您還可以列出所有可用的類型的編碼Mime::EXTENSION_LOOKUP成軌控制檯。

實施例:

控制器

class ImagesController < ApplicationController 
    def show_image 
    image_path = File.join(Rails.root, params[:path]) # or similar 
    send_file image_path, disposition: 'inline', type: 'image/jpeg', x_sendfile: true 
    end 
end 

路線

get '/image/:path', to: 'images#show_image', as: :image 

瀏覽

image_tag image_path('path_to_image') 
+0

謝謝。你是對的。類型是其中一個問題。這種方法的問題是,如果我把這個'image_tag(path_to_show_action)',圖像現在顯示在'show'視圖內。它顯示在一個新的空視圖中。所以,只顯示圖像,並且需要將該圖像與其他一些數據一起顯示在我的「show.html.erb」視圖中。 – user3339562

+0

用'send_file'行在你的控制器(路由)中添加一個不同的動作,然後你可以使用'image_tag(path_to_this_new_action)'。所以你可以在其他視圖中添加圖像。 – markets

+0

我已經添加了不同的操作,但由於某些原因'send_file'不通過。當我將頁面源檢查爲圖像源時,總是有'/ images/id_number',這是Image model的'show.html.erb'的url。 – user3339562

相關問題