How can you tell if the user is uploading a file?

4 views
Skip to first unread message

Nick Retallack

unread,
Nov 7, 2009, 9:44:07 PM11/7/09
to pylons-discuss
There are plenty of examples of how to upload files in Pylons, but
none of them check if the user actually put a file in the form or
not. If they don't, the application breaks. Wonderful.

So, how do you check? Well, I'd expect this to work:

if not request.params['file']:
return "No file was uploaded"

Unfortunately, even if the file is there it evaluates to falsy.

print "True" if request.params['file'] else "False" # always False

I did find a reliable way to test it though:

if request.params['file'] == u'':
return "No file was uploaded"

Yeah, it comes out as an empty string if there's no file. Weird. Is
this a good enough check? Will it still act this way when proxied to
by different servers?

I'm really surprised I couldn't find this information elsewhere.
Should we add this to the tutorials?
http://wiki.pylonshq.com/display/pylonsdocs/Form+Handling

Brian O'Connor

unread,
Nov 11, 2009, 11:38:54 AM11/11/09
to pylons-...@googlegroups.com
I used this when I was dealing with fileuploads:
 
 
It says it detects the absence of a file upload.
 
HTH.
Brian

Jonathan Vanasco

unread,
Nov 11, 2009, 12:05:59 PM11/11/09
to pylons-discuss
this is cobbled from a few different routines that are all chained
together....


try:
if filename not in request.POST:
raise UploadError('Missing Param')
file= request.POST[filename]
if file is None:
raise UploadError('Empty Param')
if not hasattr( file , 'filename' ):
raise UploadError("File does not hasattr 'filename'")

# validate the file
if filetype == 'image':
imageFileObject= None
imageObject= None
try:
# try to cache this all
imageFileObject= cStringIO.StringIO()
data= photofile.file.read()
imageFileObject.write(data)
imageFileObject.seek(0)
imageObject= Image.open(imageFileObject)
imageObject.load()
except exceptions.IOError:
raise UploadError('INVALID_FILETYPE')
except :
raise UploadError('INVALID_OTHER')
if not imageObject:
raise UploadError('NO_IMAGE')
Reply all
Reply to author
Forward
0 new messages