Mega Code Archive

 
Categories / Python Tutorial / CGI Web
 

Allowing Users to Upload Files via CGI Scripts

#!/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)