Skip to content
This repository
Browse code

Adding fileupload recipe

  • Loading branch information...
commit 05262462b066d2373dcb9a1ef0a27628ab58f61b 1 parent b172260
irrelative irrelative authored anandology committed

Showing 1 changed file with 45 additions and 0 deletions. Show diff stats Hide diff stats

  1. +45 0 cookbook/fileupload.md
45 cookbook/fileupload.md
Source Rendered
... ... @@ -0,0 +1,45 @@
  1 +---
  2 +layout: default
  3 +title: File Upload Recipe
  4 +---
  5 +
  6 +# File Upload Recipe
  7 +
  8 +### Problem
  9 +
  10 +File uploads can be a little tricky if you're not familiar with form uploads, or CGI in general.
  11 +
  12 +### Solution
  13 +
  14 + import web
  15 +
  16 + urls = ('/upload', 'Upload')
  17 +
  18 + class Upload:
  19 + def GET(self):
  20 + return """<html><head></head><body>
  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
  32 + web.redirect('/upload')
  33 +
  34 +
  35 + app = web.application(urls, globals())
  36 +
  37 + if __name__ == "__main__":
  38 + app.run()
  39 +
  40 +### Hang ups
  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.

0 comments on commit 0526246

Please sign in to comment.
Something went wrong with that request. Please try again.