"""This demonstrates a minimal http upload CGI.
It can operate as a standard CGI or as a CGIplus script.
It accepts a GIF, JPEG or PNG file and displays it in the browser.
"""
import cgi
import cgitb; cgitb.enable()
import importlib
import os, sys
import wasd;
HTML_TEMPLATE = """
pyRTE_test4.py
pyRTE_test4.py
"""
def print_html_form ():
"""This prints out the html form. Note that the action is set to
the name of the script which makes this is a self-posting form.
In other words, this cgi both displays a form and processes it.
"""
print ("content-type: text/html\n")
print (HTML_TEMPLATE % {'SCRIPT_NAME':os.environ['SCRIPT_NAME']})
def display_uploaded_file ():
"""This display an image file uploaded by an HTML form.
"""
form = cgi.FieldStorage()
if "image_file" not in form: return False
fileitem = form['image_file']
if not fileitem.file: return False
if not fileitem.filename: return False
filename = fileitem.filename.lower()
if filename.rfind(".gif") != -1:
print ("content-type: image/gif")
elif filename.rfind(".jpg") != -1:
print ("content-type: image/jpeg")
elif filename.rfind(".pdf") != -1:
print ("content-type: application/pdf")
elif filename.rfind(".png") != -1:
print ("content-type: image/png")
else:
print ("content-type: text/html")
print ("Only GIFs, JPEGs, PDFs and PNGs handled by this test.")
return True
print("expires: 01 Jan 2005 00:00:00 GMT\n")
sys.stdout.flush()
while 1:
chunk = fileitem.file.read()
if not chunk: break
wasd.write(chunk)
sys.stdout.flush()
del fileitem
return True
while wasd.cgiplus_begin(True):
if sys.version_info[0] < 3:
reload(cgi)
else:
importlib.reload(cgi)
if os.environ["REQUEST_METHOD"] == "POST":
display_uploaded_file ()
else:
print_html_form ()