Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 44 lines (31 sloc) 1.26 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'].value) # This is the file contents
31 web.debug(x['myfile'].filename) # This is the filename
e9e98fc sorry, haven't noticed tutorial is for webpy3...
Val-Amart authored
32 raise web.seeother('/upload')
7161e6b review for 0.23
Val-Amart authored
33
34
0526246 @irrelative Adding fileupload recipe
irrelative authored
35 if __name__ == "__main__":
e9e98fc sorry, haven't noticed tutorial is for webpy3...
Val-Amart authored
36 app = web.application(urls, globals())
37 app.run()
0526246 @irrelative Adding fileupload recipe
irrelative authored
38
be280bf @irrelative edit
irrelative authored
39 ## Hang ups
0526246 @irrelative Adding fileupload recipe
irrelative authored
40
41 A couple of things to watch out for:
42
43 * The form needs an attribute enctype="multipart/form-data", or this won't work correctly.
44 * 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.