Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 45 lines (32 sloc) 1.337 kb
0526246 @irrelative Adding fileupload recipe
irrelative authored
1 ---
2 layout: default
3 title: File Upload Recipe
4 ---
5
6 # File Upload Recipe
7
be280bf @irrelative edit
irrelative authored
8 ## Problem
0526246 @irrelative Adding fileupload recipe
irrelative authored
9
10 File uploads can be a little tricky if you're not familiar with form uploads, or CGI in general.
11
be280bf @irrelative edit
irrelative authored
12 ## Solution
0526246 @irrelative Adding fileupload recipe
irrelative authored
13
14 import web
15
16 urls = ('/upload', 'Upload')
17
18 class Upload:
19 def GET(self):
e9e98fc sorry, haven't noticed tutorial is for webpy3...
Val-Amart authored
20 return """<html><head></head><body>
0526246 @irrelative Adding fileupload recipe
irrelative authored
21 <form method="POST" enctype="multipart/form-data" action="">
22 <input type="file" name="myfile" />
23 <br/>
24 <input type="submit" />
25 </form>
26 </body></html>"""
27
28 def POST(self):
29 x = web.input(myfile={})
30 web.debug(x['myfile'].filename) # This is the filename
11e2d09 edit
Andrei Savu authored
31 web.debug(x['myfile'].value) # This is the file contents
32 web.debug(x['myfile'].file.read()) # Or use a file(-like) object
e9e98fc sorry, haven't noticed tutorial is for webpy3...
Val-Amart authored
33 raise web.seeother('/upload')
7161e6b review for 0.23
Val-Amart authored
34
35
0526246 @irrelative Adding fileupload recipe
irrelative authored
36 if __name__ == "__main__":
e9e98fc sorry, haven't noticed tutorial is for webpy3...
Val-Amart authored
37 app = web.application(urls, globals())
38 app.run()
0526246 @irrelative Adding fileupload recipe
irrelative authored
39
be280bf @irrelative edit
irrelative authored
40 ## Hang ups
0526246 @irrelative Adding fileupload recipe
irrelative authored
41
42 A couple of things to watch out for:
43
44 * The form needs an attribute enctype="multipart/form-data", or this won't work correctly.
45 * In the webpy code, a default value is needed (the myfile={} part) if you want it to be imported as a CGI FieldStorage object. If you don't specify the default value, the file will be passed as a string -- this works, but you lose the filename attribute.
Something went wrong with that request. Please try again.