Python Upload CGI: Difference between revisions

From XPUB & Lens-Based wiki
(Created page with "See also examples like Woof. == Simple Upload CGI == <source lang="python"> #!/usr/bin/env python import cgitb; cgitb.enable() import cgi, os env = os.environ method =...")
 
No edit summary
 
Line 1: Line 1:
See also examples like [[Woof]].
For a self-contained server with upload capability see examples like [[Woof]].


== Simple Upload CGI ==
== Simple Upload CGI ==
If you have a webserver with basic CGI support, this script displays and processes a simple upload form to receive files.
<source lang="python">
<source lang="python">
#!/usr/bin/env python
#!/usr/bin/env python

Latest revision as of 13:25, 13 January 2014

For a self-contained server with upload capability see examples like Woof.

Simple Upload CGI

If you have a webserver with basic CGI support, this script displays and processes a simple upload form to receive files.

#!/usr/bin/env python

import cgitb; cgitb.enable()
import cgi, os


env = os.environ
method = os.environ.get("REQUEST_METHOD")

print "Content-type:text/html;charset=utf-8"
print
# print "Hello", method
# cgi.print_environ()

UPLOADS = "/var/www/uploads/"

def upload (inputname, upload_dir):
    form = cgi.FieldStorage()
    if not form.has_key(inputname): return
    fileitem = form[inputname]
    if not fileitem.file: return
    fp = os.path.join(upload_dir, fileitem.filename)
    fout = file (fp, 'wb')
    bytes = 0
    while 1:
        chunk = fileitem.file.read(100000)
        if not chunk: break
        bytes += len(chunk)
        fout.write (chunk)
    fout.close()
    return bytes, fileitem.filename

if method == "POST":
    result = upload("thefile", UPLOADS)
    if result:
        bytes, filename = result
        print "{0} bytes written to {1}<br />".format(bytes, filename)
        print "<a href="">upload another</a>"
else:
    print """<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="thefile" /><input type="submit" />
</form>
</body>
</html>
"""