2015-11-20 54 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

为什么麻烦从客户端的网址,而你可以处理和过滤它从服务器。永远不要相信任何客户:) –