Skip to content

Instantly share code, notes, and snippets.

@maltefiala
Last active August 29, 2015 14:27
Show Gist options
  • Save maltefiala/95fbcf2d89c4961e6271 to your computer and use it in GitHub Desktop.
Save maltefiala/95fbcf2d89c4961e6271 to your computer and use it in GitHub Desktop.
CherryPy Writing Uploads
#!/bin/env python3.4
# mainly copied from https://cherrypy.readthedocs.org/en/3.2.6/progguide/files/uploading.html
import os
localDir = os.path.dirname(__file__) # current working directory
absDir = os.path.join(os.getcwd(), localDir) # os.getcwd() : Return a string representing the current working directory.
import cherrypy
class FileDemo(object):
def index(self):
return """
<html><body>
<h2>Upload a file</h2>
<form action="upload" method="post" enctype="multipart/form-data">
filename: <input type="file" name="myFile" /><br />
<input type="submit" />
</form>
</body></html>
"""
index.exposed = True
def upload(self, myFile):
out = """<html>
<body>
myFile length: %s<br />
myFile filename: %s<br />
myFile mime-type: %s
</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.
size = 0
whole_data = bytearray() # Neues Bytearray
while True:
data = myFile.file.read(8192)
whole_data += data # Save data chunks in ByteArray whole_data
if not data:
break
size += len(data)
written_file = open(myFile.filename, "wb") # open file in write bytes mode
written_file.write(whole_data) # write file
return out % (size, myFile.filename, myFile.content_type)
upload.exposed = True
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())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment