How do I upload files via a CGI script?

Greg Jorgensen greg at pdxperts.com
Thu May 24 03:29:59 EDT 2001


On 23 May 2001, Ben Briggs wrote:

> I'm having the toughest time finding out how to upload a file via a
> CGI script. I would prefer to use the cgi module, but I'll use
> anything that works.

Assuming your HTML page has the form and file input set up correctly, the
cgi module can get the uploaded file easily. Here's the example from the
excellent book "Python Essential Reference" by David Beazley, modified to
assume a binary (non-text) file is uploaded and you want to save it on
the web server with the same name as it has on the client computer:

    fileitem = form["userfile"]    # userfile is the form input field name
    if fileitem.file:
        savefile = open(fileitem.name, "wb")  # create file on server
        while 1:
            buf = fileitem.file.read(2048)
            if not buf: break
            savefile.write(buf)
        savefile.close()

-- 
Greg Jorgensen
PDXperts LLC
Portland, Oregon USA
gregj at pobox.com




More information about the Python-list mailing list