[Tutor] File uploads perr HTTP

Michael P. Reilly arcege@shore.net
Thu, 22 Feb 2001 15:49:04 -0500 (EST)

> can someone point me to a URL where I can RTFM "file uploads per HTTP in
> Python" for dummies? I would be extremly nice if  someone posted a snippe=
> t
> to the list, that would give me a push in the right direction.

I don't know about a generalized document for file uploads (I assume
through a <INPUT type="file"> tag).  But Python can certainly support
this through the cgi.py module.  What happens is that instead of the
usual application/x-www-form-urlencoded Mime type, multipart/form-data
is sent from the client (this is ONLY for post method forms).  Within
the Mime data is the contents of the file, this is accessible from
the CGI form object.  Read the cgi.__doc__ doc string for a semi-
decent explaination.

import cgi
form = cgi.FieldStorage()
if form.has_key('file'):  # from <INPUT name="file"...>
    fileitem = form['file']
    if fileitem.file:
        contents = []
        line = fileitem.file.readline()
        while line:
            bytes = len(len)
            contents.append( line )
            line = fileitem.file.readline()
            if fileitem.length != -1 and fileitem.length != bytes:
                raise ValueError("data read not same as Content-Length")
        # get the client-given filename, the contents and length
        file = (fileitem.filename, contents, fileitem.length)

Or instead of reading all the lines, you can open a new file (in a
location accessible to the web server) and write the thumbnail data to

About the only other documentation that I've found for this is in
O'Reilly's "CGI Programming on the World Wide Web" (it's a perl based
book *blech*).

Good luck,

| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |