Allowing Users to Upload Files via CGI Scripts : File Upload « CGI Web « Python Tutorial






#!/usr/bin/pythonimport cgi, os, sys, string
import posixpath, macpath

saveDir = "/upload"

sys.stderr = sys.stdout

data = cgi.FieldStorage()

def saveFile(uFile):
    fPath = "%s/%s" % (saveDir, uFile.filename)
    buf = uFile.file.read()
    bytes = len(buf)
    sFile = open(fPath, 'wb')
    sFile.write(buf)
    sFile.close()


webText = """Content-type: text/html\n"
<title>CGI Upload Form</title>\n
<h2>Upload File</h2><paragraph>"""
print webText

if data.has_key('uFile'):
    saveFile(data['uFile'])
    print "<b>%s</b> uploaded (%d bytes)." % (data['uFile'].filename, bytes)








22.6.File Upload
22.6.1.Allowing Users to Upload Files via CGI Scripts
22.6.2.Load file
22.6.3.Post file content