Web2py: How should I display an uploaded image that is stored in a database?

痞子三分冷 提交于 2019-12-20 09:42:06

问题


Is there a web2py way of displaying images from a database table?

Example:

The model:

db.define_table=('images',Field('picture', 'upload' ))

The controller:

def somefunction(): to get the image.

How exactly should I "read" a picture from the database?

The view:

<img src="{{somefunction}}" />

回答1:


As is, your model will not store the image in the database -- instead, it will store the image on the filesystem, with its new filename stored in the database (in the 'picture' field). If you want to store the image itself in the database, use the following:

db.define_table('images',
    Field('picture', 'upload', uploadfield='picture_file')
    Field('picture_file', 'blob'))

Whether you store the images on the filesystem or in the database, you can use the same method to retrieve them. The 'welcome' scaffolding application includes the following download() action in the default.py controller:

def download():
    return response.download(request, db)

To retrieve an image, just do something like:

<img src="{{=URL('default', 'download', args=picture_name)}}" />

where picture_name is the value stored in the 'picture' field of the 'images' table for the particular image you want to retrieve.

For more details, see here and here.

If you need further help, try asking on the mailing list.




回答2:


Alternatively, if you use web2py's default way of uploading images as files, you can use:

In models:

db.define_table('images',Field('picture','upload'))

In controllers:

def somefunction():
    pic = db(db.images).select().first().picture   #select first picture
    return dict(pic=pic)

And in the default/somefunction.html view:

{{extend 'layout.html'}}
<img  src="{{=URL( 'download', args=pic)}}" />

I know this is a while after the original question but thought it might be useful as it took me a while to figure out.



来源:https://stackoverflow.com/questions/6334360/web2py-how-should-i-display-an-uploaded-image-that-is-stored-in-a-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!