Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 47 lines (33 sloc) 1.401 kB
0526246 @irrelative Adding fileupload recipe
irrelative authored
1 ---
2 layout: default
3 title: File Upload Recipe
4 ---
5
6 # File Upload Recipe
7
c5d0e6a Add link to french translation
nux authored
8 Other languages: [français](/../cookbook/fileupload/fr) | ...
9
be280bf @irrelative edit
irrelative authored
10 ## Problem
0526246 @irrelative Adding fileupload recipe
irrelative authored
11
12 File uploads can be a little tricky if you're not familiar with form uploads, or CGI in general.
13
be280bf @irrelative edit
irrelative authored
14 ## Solution
0526246 @irrelative Adding fileupload recipe
irrelative authored
15
16 import web
17
18 urls = ('/upload', 'Upload')
19
20 class Upload:
21 def GET(self):
e9e98fc sorry, haven't noticed tutorial is for webpy3...
Val-Amart authored
22 return """<html><head></head><body>
0526246 @irrelative Adding fileupload recipe
irrelative authored
23 <form method="POST" enctype="multipart/form-data" action="">
24 <input type="file" name="myfile" />
25 <br/>
26 <input type="submit" />
27 </form>
28 </body></html>"""
29
30 def POST(self):
31 x = web.input(myfile={})
32 web.debug(x['myfile'].filename) # This is the filename
11e2d09 edit
Andrei Savu authored
33 web.debug(x['myfile'].value) # This is the file contents
34 web.debug(x['myfile'].file.read()) # Or use a file(-like) object
e9e98fc sorry, haven't noticed tutorial is for webpy3...
Val-Amart authored
35 raise web.seeother('/upload')
7161e6b review for 0.23
Val-Amart authored
36
37
0526246 @irrelative Adding fileupload recipe
irrelative authored
38 if __name__ == "__main__":
e9e98fc sorry, haven't noticed tutorial is for webpy3...
Val-Amart authored
39 app = web.application(urls, globals())
40 app.run()
0526246 @irrelative Adding fileupload recipe
irrelative authored
41
be280bf @irrelative edit
irrelative authored
42 ## Hang ups
0526246 @irrelative Adding fileupload recipe
irrelative authored
43
44 A couple of things to watch out for:
45
46 * The form needs an attribute enctype="multipart/form-data", or this won't work correctly.
47 * 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.