2015-11-20 32 views
-6

例如,我在項目中有url:http://localhost:3000/images/20/thumb/300x300。 300x300 - 動態寬度和圖像高度的url中的動態參數。我如何加密這個網址?可以通過爲http頭添加令牌?我需要這個來保護服務器生成不同寬度和高度的圖像(100x100,150x200,300x200 ...)顯示代碼示例。如何在rails中加密url

+2

你是什麼意思加密url? –

+2

請更具體地說明,爲什麼要加密url?你有什麼試過,你的問題是什麼?你能給我們一個你想實現的加密url的例子嗎? –

+0

您可能對「加密」有不正確的理解? – MWiesner

回答

0

您可以在您的路線使用:

get 'images/:id/thumb/:size', size: /^[0-9]+x[0-9]+$/ 

,並在你的控制器,你可以這樣訪問圖像的ID和大小:

def show 
    @image= Image.find(params[:id]) 
    width, height=params[:size].split("x").map{|s| s.to_i} 
    # ... 
end 

如果您有圖像的幾個固定的大小你接受那麼你可以使用約束如下:

Rails.application.routes.draw do 
get 'images/:id/thumb/:size', size: /^[0-9]+x[0-9]+$/, 
    constraints: ImageSizeConstraint.new 
end 

class ImageSizeConstraint 
    def matches?(request) 
    params = request.path_parameters 

    if %w(100x100 150x200 300x200).include? params[:size] 
     return true 
    else 
     return false 
    end 
    end 
end 
+0

此功能已完成。如何保護服務器生成不同的:在URL中的大小? – edenisn

+0

更新了我的答案,讓我知道是否有幫助。 – sadaf2605

+0

謝謝sadaf2605 – edenisn

0

從你的問題我知道nd您希望服務器僅渲染可接受的維度中的一個。所以,而不是加密的URL,你可以只是在你的控制器中過濾

... 
ALLOW_THUMB_SIZES = %w(100x100 150x200 300x200) 
... 
def generate_image 
    thumb_size = params[:thumb_size] 
    if ALLOW_THUMB_SIZES.include? thumb_size 
    # do resize image to thumb_size here 
    else 
    # resize to some default size e.g. 300x300 
    # or throw exception... 
    end 
end 
... 
+0

也許,作爲一個變種 – edenisn

+0

爲什麼麻煩從客戶端的網址,而你可以處理和過濾它從服務器。永遠不要相信任何客戶:) –