2010-10-14 32 views
0

如何返回respond_to do |format|塊內的圖像?返回與respond_to圖像

我已經有圖像完全組裝(即從博客沒有醜陋的裝配),並在一個特定的URL(因爲它在公共文件夾中),我只需要能夠返回該圖像的特定其他網址查詢。

例如,圖像是

public/cars/userid/car_id/random_name.JPG 

,我希望能夠當用戶進入

http://mywebsite.com/car_id.JPG 

,因爲它是望而卻步讓用戶不得不就可以提供這種形象知道useridrandom_name。我的網址public/cars/userid/car_id/random_name.JPG已經作爲@car.public_filename,因爲@carattachment_fu對象。

回答

1

您可以將瀏覽器重定向到圖像:

redirect_to @car.public_filename 
+0

對不起,我想我應該更清楚。我想隱藏用戶的存儲細節。 [*編輯*:重新編寫關於在頁面中嵌入圖像的重定向評論;好像從這個角度來看應該沒問題。] – unsorted 2010-10-14 10:38:34

+0

另外,當我告訴rails響應format.jpg時,它給了我一個關於不存在的MimeType JPG的錯誤。任何想法如何使它處理呢?感謝您的快速響應。 – unsorted 2010-10-14 10:39:13

+0

圖像的MIME類型格式如下:''image/jpg'',''image/jpeg'',''image/png'','image/gif''等。如果不添加圖像MIME類型在默認情況下,請參閱Matt關於如何註冊其他類型的其他答案。 – Jeremy 2010-10-14 11:18:21

0

如果你想在respond_to使用另一種MIME類型,你可以在config/initializers/mime_types.rb添加。這裏有一個例子:

Mime::Type.register "text/richtext", :rtf 
1

你也可以寫一個小的金屬中間件重新路由所有/car_id.JPG URL到真正的文件:

#app/metal/serve_car.rb 
# Allow the metal piece to run in isolation 
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails) 

class ServeCar 
    def self.call(env) 
    if env["PATH_INFO"] =~ /^\/car_(\d+).JPG$/ 
     path = Car.find($1).public_filename 
     [302, {"Content-Type" => "text/html", "Location" => path}, ["You are being redirected"]] 
    else 
     [404, {"Content-Type" => "text/html"}, ["Not Found"]] 
    end 
    end 
end