| 1 |
import cherrypy |
|---|
| 2 |
from cherrypy.lib.filter import basefilter |
|---|
| 3 |
|
|---|
| 4 |
import cgi |
|---|
| 5 |
|
|---|
| 6 |
class StreamFilter(basefilter.BaseFilter): |
|---|
| 7 |
|
|---|
| 8 |
def beforeRequestBody(self): |
|---|
| 9 |
if cherrypy.request.path == '/postFile': |
|---|
| 10 |
|
|---|
| 11 |
|
|---|
| 12 |
if ('Content-Length' in cherrypy.request.headerMap and |
|---|
| 13 |
cherrypy.request.method == 'POST'): |
|---|
| 14 |
|
|---|
| 15 |
cherrypy.request.processRequestBody = False |
|---|
| 16 |
else: |
|---|
| 17 |
|
|---|
| 18 |
pass |
|---|
| 19 |
|
|---|
| 20 |
|
|---|
| 21 |
class Root: |
|---|
| 22 |
_cpFilterList = [StreamFilter()] |
|---|
| 23 |
|
|---|
| 24 |
def index(self): |
|---|
| 25 |
return """ |
|---|
| 26 |
<html><body> |
|---|
| 27 |
<form method=post action=postFile enctype="multipart/form-data"> |
|---|
| 28 |
Upload a file: <input type=file name=myFile><br> |
|---|
| 29 |
<input type=submit> |
|---|
| 30 |
</form> |
|---|
| 31 |
</body></html> |
|---|
| 32 |
""" |
|---|
| 33 |
index.exposed = True |
|---|
| 34 |
|
|---|
| 35 |
def postFile(self): |
|---|
| 36 |
|
|---|
| 37 |
|
|---|
| 38 |
|
|---|
| 39 |
lowerHeaderMap = {} |
|---|
| 40 |
for key, value in cherrypy.request.headerMap.items(): |
|---|
| 41 |
lowerHeaderMap[key.lower()] = value |
|---|
| 42 |
|
|---|
| 43 |
|
|---|
| 44 |
|
|---|
| 45 |
dataDict = cgi.FieldStorage(fp=cherrypy.request.rfile, |
|---|
| 46 |
headers=lowerHeaderMap, |
|---|
| 47 |
environ={'REQUEST_METHOD':'POST'}, |
|---|
| 48 |
keep_blank_values=1) |
|---|
| 49 |
|
|---|
| 50 |
value = dataDict['myFile'] |
|---|
| 51 |
|
|---|
| 52 |
|
|---|
| 53 |
|
|---|
| 54 |
|
|---|
| 55 |
|
|---|
| 56 |
|
|---|
| 57 |
|
|---|
| 58 |
|
|---|
| 59 |
f = open('/tmp/myFile', 'wb') |
|---|
| 60 |
while 1: |
|---|
| 61 |
data = value.file.read(1024 * 8) |
|---|
| 62 |
if not data: break |
|---|
| 63 |
f.write(data) |
|---|
| 64 |
f.close() |
|---|
| 65 |
|
|---|
| 66 |
return "<html><body>The file has been saved in /tmp/myFile</body></html>" |
|---|
| 67 |
postFile.exposed = True |
|---|
| 68 |
|
|---|
| 69 |
cherrypy.root = Root() |
|---|
| 70 |
cherrypy.server.start() |
|---|