How to upload a file without using SQLFORM ??

1,880 views
Skip to first unread message

antimatter

unread,
Jun 27, 2010, 6:20:36 AM6/27/10
to web2py-users
Hi,
how do I upload a file in web2py without using SQLFORM ?
So far, I've got my view with a HTML form:

<form method="post" enctype="multipart/form-data">
<input name="upload" type="file" size="60" maxlength="100000">
<input type="Submit" value="Upload">
</form>

Now, how do I write a controller, which uploads the file and save's it
to a specified folder?
But everytime I select a file and upload it, request.vars.upload is
None. How does it work?

Best regards
antimatter

mdipierro

unread,
Jun 27, 2010, 6:56:27 AM6/27/10
to web2py-users
something like this

def youraction():
import shutil
if form.vars:
filename=request.vars.upload.filename
file=request.vars.upload.file
shutil.copyfileobj(file,open('path/'+filename,'wb'))
return dict()

but mind that open('path/'+filename,'wb') is vulnerable to directory
traversal attacks unless you validate or cleanup the filename.

antimatter

unread,
Jun 28, 2010, 12:55:21 PM6/28/10
to web2py-users
That works. Thank you very much.

But this solution leads to the next thing.
This upload form (created by the FORM helper) interferes with an
already existing form.

The first form has some text fields, one of them is mandatory. The
form accepts with keepvalues = True.
When I fill in some values in the first form and then upload a file
via the upload form on the same page before submitting the first form,
it will reset the first form.
The accept() methods don't use the session variable as explained by
the book.

Any ideas how I can prevent this from happening?

mdipierro

unread,
Jun 28, 2010, 4:03:20 PM6/28/10
to web2py-users
Try give it a name

form.accepts(....,formname='test')

Rogere Questre

unread,
Dec 30, 2013, 1:01:40 AM12/30/13
to web...@googlegroups.com, andreas...@googlemail.com
In my Case it says 

 'str' object has no attribute 'filename'

Reply all
Reply to author
Forward
0 new messages