How to use uploaded image

176 views
Skip to first unread message

michael sun

unread,
Jul 26, 2015, 12:41:06 AM7/26/15
to web2py-users
I build a table:

db.define_table('image',
   Field('title', unique=True),
   Field('file', 'upload'),
   format = '%(title)s')

then upload a image called 'water'.

in index.html, I wrote:
<img src="{{=URL('download',args=db.image.water)}}" />

but then it gives me the error:

<type 'exceptions.AttributeError'>()
Function argument list

(self=<Table image (id,title,file)>, key='water')

Code listing
343.
344.
345.
346.
347.
348.

349.
350.
351.
352.

def __getattr__(self, key):
try:
return self.__dict__.__getitem__(str(key))
except:
raise AttributeError


def __setitem__(self, key, value):
self.__dict__.__setitem__(key, value)

Anthony

unread,
Jul 26, 2015, 8:46:05 AM7/26/15
to web2py-users, michaelsu...@gmail.com, michaelsu...@gmail.com
First, three corrections:
  • The upload field does not name the stored file the same as the name of the uploaded file. The stored file gets renamed, with the new name including an encoded version of the original filename (which gets decoded upon retrieveal). It is this new filename that actually gets stored in the upload field (the file itself is stored on the filesystem).
  • The attribute after a table name is a field name, not the name of an uploaded file, so you would do db.image.file (db.image.water makes no sense, as the table does not include a field named "water").
  • The URL argument passed to the download function to indicate which file to download must be the filename stored in the upload field, not a Field object.
So, to display a given image, you must somehow be able to query the database to retrieve the image you want, and then access the "file" field of that record to get the filename, which you will then pass as a URL arg to the download function. For example:

In a controller:

    row = db(db.image.title == 'some title').select().first()

In the view:

<img src="{{=URL('default', 'download', args=row.file)}}

Anthony

michael sun

unread,
Jul 30, 2015, 5:40:25 PM7/30/15
to web2py-users, abas...@gmail.com
Hi Anthony, sorry about the late reply. Thank you very much for your detailed answers.
Reply all
Reply to author
Forward
0 new messages