2013-07-16 91 views
0

我正在使用Web2Py,用户图像是动态的,必须从同一服务器中的不同系统加载,因此无法将它们移动到包含在web2py应用程序目录中。所以我不能有相对路径的图像。 Symbolink链接不是一个选项。Web2py:从动作调用或Web服务调用服务图像

我在想这个解决方案可能是从一个动作调用或Web服务提供JPG图像,这样应用程序就可以访问本地文件并以编程方式返回它,而不必移动一个图像。例如,一个视图有以下代码:

<li class="file ext_jpg"> 
    <figure class="image_container"> 
     <img src="controller_name/action_serving_images/unique_id_genereted_for_this_image.jpg" alt=""> 
    </figure> 
</li> 

具有操作:

def action_serving_images(image_id) 
    #obtain image based on it's unique generated id 
    return image 

或者用于该服务的情况下:

<li class="file ext_jpg"> 
    <figure class="image_container"> 
     <img src="controller_name/service_serving_images/jpg/image/unique_id_genereted_for_this_image.jpg" alt=""> 
    </figure> 
</li> 

具有服务:

def service_serving_images(): 
    return service() 

@service.jpg 
def image(image_id): 
    #obtain image based on it's unique generated id 
    return image 
  1. 是否有这些选项可能?
  2. 如何获取图像并将其作为字节流以适当的内容类型返回,以便浏览器可以正确渲染它?
  3. 在服务的情况下,我是否需要为JPG创建特殊的装饰器?怎么样?

回答

2

这比这更容易。

首先创建一个这样的动作:

def serve_image(): 
    id = request.args(0) 
    filename = get_image_filename_from(id) 
    stream = open(filename,'rb') 
    return response.stream(stream, attachment=True, filename=filename) 

然后在你的看法,你做的事:

<img src="{{=URL('serve_image',args='1234')}}" /> 

,其中1234是您想要的图像的ID。

+0

这绝对是这样的,只有3改变我作出或它的工作: (1)加入reques反对响应 (2)设置固定为False (3)使用'vars'发送图像ID,而不是'args' urllib引用,使用参数给我带来了太多的斜线和加号的麻烦 'return response.stream(stream,request = request,attachment = False,filename = filename)''{{= URL('serve_image' ,乏= '1234')}}' – sapeish