I recently needed to handle file uploads from a Flash form post using CGI and Python. I made two discoveries:
- Python’s CGI library ignores query string variables on POST requests.
- 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:
[source:python]#!/usr/bin/python
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:
return
# 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”
else:
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
fileObj.write(chunk)
fileObj.close()
[/source]
Bonus points for checking for and creating a new directory to store the uploaded file in, if needed.
Tags: apache, cgi, HTML, python