Filenames of cgi-uploaded files

Karl Svensson karl-sve at dsv.su.se
Tue Jan 11 11:08:08 EST 2000


Hello!

On Mon, 10 Jan 2000, Sposhua wrote:
> Uploading a file from a form - I need to know the filename (to ignore all
> non-gif/jpg uploads) and filesize. Can't find anything in the tutorials on
> theis :-( Then I guess I upload the pic using
> 
> form = cgi.FieldStorage
                         ^
dont forget the (), should be cgi.FieldStorage()...

> fileitem = form['picture']
> if fileitem.file:
> 	pic_upload = fileitem.file.read()
> 
> (adapted from the tutorial, though it doesn't make much sense to me -
> expecially the fileitem.file bit)

When in doubt, consult the source... :)

In the docstring of the FieldStorage class in cgi.py is:

"... it has the following attributes:
...
filename: the filename, if specified ...
...
file: the file(-like) object from which you can read the data;
   None if the data stored is a simple string ..."

So

form = cgi.FieldStorage()
fileitem = form['picture']
# if image is gif or jpg
if fileitem.file and ((string.find('.gif',fileitem.filename) != -1) or \
(string.find('.jpg',fileitem.filename) != -1)):
    # read file data to memory
    imagefile_data = fileitem.file.read()
    # to get filesize
    imagefile_length = len(imagefile_data)

might work.
I haven't tested it, so I'm not sure...
The string.find bits could surely be more elegantly written with regex,
but I don't know how, I'm quite new to Python myself. Please tell me of
any errors.

HTH

/Kalle Svensson, just another guy...




More information about the Python-list mailing list