Skip to content

Instantly share code, notes, and snippets.

@snahor
Created June 18, 2013 18:18
Show Gist options
  • Save snahor/5807886 to your computer and use it in GitHub Desktop.
Save snahor/5807886 to your computer and use it in GitHub Desktop.
import os
localDir = os.path.dirname(__file__)
absDir = os.path.join(os.getcwd(), localDir)
import cherrypy
class FileDemo(object):
def index(self, myFile=None, derp_cv=None, **kwargs):
if cherrypy.request.method == "POST":
out = """
myFile length: %s<br />
myFile filename: %s<br />
myFile mime-type: %s
"""
html = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>%s</p>
<p>%s</p>
</body>
</html>
"""
# Although this just counts the file length, it demonstrates
# how to read large files in chunks instead of all at once.
# CherryPy reads the uploaded file into a temporary file;
# myFile.file.read reads from that.
sizex = 0
while True:
data = myFile.file.read(8192)
if not data:
break
sizex += len(data)
sizey = 0
while True:
data = derp_cv.file.read(8192)
if not data:
break
sizey += len(data)
x = out % (sizex, derp_cv.filename, derp_cv.content_type)
y = out % (sizey, myFile.filename, myFile.content_type)
return html % (x, y)
else:
return """
<html><body>
<h2>Upload a file</h2>
<form action="" method="post" enctype="multipart/form-data">
filename: <input type="file" name="myFile" /><br />
filename: <input type="file" name="derp_cv" /><br />
<input id="" type="text" name="derp" />
<input type="submit" />
</form>
<h2>Download a file</h2>
<a href='download'>This one</a>
</body></html>
"""
index.exposed = True
#tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf')
if __name__ == '__main__':
# CherryPy always starts with app.root when trying to map request URIs
# to objects, so we need to mount a request handler root. A request
# to '/' will be mapped to HelloWorld().index().
cherrypy.quickstart(FileDemo(), '/')
else:
# This branch is for the test suite; you can ignore it.
cherrypy.tree.mount(FileDemo(), config=tutconf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment