If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

This demonstrates how to manually handle file uploads in web2py (without any SQLForm magic.)


    Field('file', 'upload'),
    format = '%(title)s')


def download(): return response.download(request,db)
def link(): return response.download(request,db,attachment=False)

def index():
	image_form = FORM(
	if image_form.accepts(request.vars,formname='image_form'):
		image = db.image.file.store(image_form.vars.image_file.file, image_form.vars.image_file.filename)
		id = db.image.insert(file=image,title=image_form.vars.image_title)
	images = db().select(db.image.ALL)
	return dict(images=images)


{{extend "layout.html"}}

<form action="" enctype="multipart/form-data" method="post">
	<input name="_formname" type="hidden" value="image_form">
	<input class="string" name="image_title" type="text" value="">
	<input class="upload" name="image_file" type="file">
	<input type="submit" value="Submit">

{{for image in images:}}
		<a href="{{=URL(f='link', args=image.file)}}">
			<img src="{{=URL(f='link', args=image.file)}}"/>
		<a href="{{=URL(f='download', args=image.file)}}">

(Of course we could just use the serialized form in the view, but I like to render my views by hand to show what's going on)






Related slices

Comments (1)

  • Login to post

  • 0
    joecodeswell 12 years ago

    Hi Yarin,


    This is just what i was looking for. I found a small nit however. When i first ran the code, i got an error with a ticket that said:

    "UnboundLocalError: local variable 'images' referenced before assignment." referring to the controller  statement at line 18 "

    return dict(images=images)


    I put this statement "images = [] # needed this on first go around" just before the if and things seemed to go smoothly.

    Thanks again, for a great recipe.

    Love and peace,



    replies (1)
    • ykessler 12 years ago

      Hey Joe,

      Not sure how you got that error- just retested and it worked no prob. Anyway, glad you found it useful. -Y

Hosting graciously provided by:
Python Anywhere