Commit 8cb6b200 authored by Michael Hanus 's avatar Michael Hanus

Add example for file upload

parent 2eb0585f
This directory contains an example (`UploadFile.curry`)
to demonstrate a file upload form with the help of a simple Python script.
See <>
for the documentation of the Python/CGI library
used in this example.
-- An example to demonstrate a file upload form with the help
-- of a simple Python script.
import Directory ( doesFileExist )
import HTML.Base
-- The upload form is defined as a raw search form since the handler
-- is written in Python. The handler script must be stored in file
-- `upload-handler.cgi`.
-- The arguments are the base name of the file where the contents
-- of the uploaded file is stored, and the URL loaded after
-- uploading the file.
uploadForm :: String -> String -> HtmlExp
uploadForm uploadfilename redirecturl =
HtmlStruct "form" [("method","post"), ("action","upload-handler.cgi"),
[hiddenField "UPLOADNAME" uploadfilename,
hiddenField "REDIRECT" redirecturl,
HtmlStruct "input" [("type","file"), ("name","FILENAME")] [],
HtmlStruct "input" [("type","submit"), ("value", "Upload!")] []
-- main HTML page containing the form
main :: IO HtmlPage
main = do
uparam <- getUrlParameter
if null uparam -- Initial call
then return $ page "Upload Form"
[ h3 [htxt "Please select a file to upload:"],
uploadForm upfile "uploadform.cgi?next" ]
else do
exfile <- doesFileExist upfile
if exfile
then do cnt <- readFile upfile
return $ page "UploadForm"
[h3 [htxt "Contents of the uploaded file:"],
verbatim cnt]
else return $ page "UploadForm" [h3 [htxt "No file uploaded!"]]
upfile = "UploadedFile"
-- Install with:
-- > cypm exec curry2cgi -o ~/public_html/cgi-bin/uploadform.cgi UploadFile
-- > cp -p upload-handler.cgi ~/public_html/cgi-bin/
# A simple script to upload a file with a CGI form
# Import modules for CGI handling
import cgi, os
import cgitb; cgitb.enable() # for debugging only
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get filename from field FILENAME
fileitem = form['FILENAME']
# Get desired upload file name from field UPLOADNAME
if form.getvalue('UPLOADNAME'):
upname = form.getvalue('UPLOADNAME')
upname = "UNNAMED"
# Test if the file was uploaded
if fileitem.filename:
# strip leading path from upload file name to avoid
# directory traversal attacks
upfn = os.path.basename(upname)
open(upfn, 'wb').write(
message = 'File "' + fileitem.filename + '" successfully uploaded to "' + upfn + '"'
message = 'No file uploaded'
# Redirect to a URL if defined by field REDIRECT
if form.getvalue('REDIRECT'):
print "Location: " + form.getvalue('REDIRECT')
print ""
print "Content-Type: text/html"
print ""
print "<html>"
print "<body>"
print " <p>%s</p>" % (message,)
print "</body>"
print "</html>"
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment