Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

FileUpload: streamfilter.py

Line 
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             # if you don't check that it is a post method the server might
11             # lock up. we also check to make sure something was submitted.
12             if ('Content-Length' in cherrypy.request.headerMap and
13                 cherrypy.request.method == 'POST'):
14                 # Tell CherryPy not to parse the POST data itself for this URL
15                 cherrypy.request.processRequestBody = False
16             else:
17                 # the file is empty; you might want to redirect.
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         # Note: we could check Content-Length here and bail out if it's too big
37        
38         # Create a copy of cherrypy.request.headerMap with lower keys
39         lowerHeaderMap = {}
40         for key, value in cherrypy.request.headerMap.items():
41             lowerHeaderMap[key.lower()] = value
42        
43         # Use cgi.FieldStorage to parse the POST data.
44         # This will store the uploaded file in a tempfile
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         # Value has 2 attributes:
53         #    - filename contains the name of the uploaded file
54         #    - file is an input stream opened for reading
55        
56         # Read the tempfile and store it in the final file
57         # Note that you'd have to carefully choose the filename if you want to
58         # be thread-safe
59         f = open('/tmp/myFile', 'wb')
60         while 1:
61             data = value.file.read(1024 * 8) # Read blocks of 8KB at a time
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()

Hosted by WebFaction

Log in as guest/cpguest to create tickets