I recently needed to handle file uploads from a Flash form post using CGI and Python. I made two discoveries:

  1. Python’s CGI library ignores query string variables on POST requests.

  2. After you’ve done it once, working with POST variables whether uploaded files or otherwise is dead simple!

Here is the file I came up with:

import cgi, sys, os

UPLOAD_DIR = "/home/user/uploads"

postVars = cgi.FieldStorage()

if postVars.has_key("myFile"):
    fileitem = postVars["myFile"]

    # If myFile doesn't contain a FILE, exit
    if not fileitem.file:

    # Strip file extension
    (name,ext) = os.path.splitext( fileitem.filename )
    # If a binary file, ensure write flags are binary
    if ext == ".jpg" or ext == ".png" or ext == ".gif":
        ioFlag = "wb"
        ioFlag = "w"
    # Save file data to disk stream        
    fileObj = file(os.path.join(self.path, fileitem.filename),ioFlag)
    while 1:
        chunk = fileitem.file.read(100000)
        if not chunk: break

Bonus points for checking for and creating a new directory to store the uploaded file in, if needed.