home > File Upload Recipe

File Upload Recipe

Problem

File uploads can be a little tricky if you're not familiar with form uploads, or CGI in general.

Solution

import web

urls = ('/upload', 'Upload')

class Upload:
    def GET(self):
        return """<html><head></head><body>
<form method="POST" enctype="multipart/form-data" action="">
<input type="file" name="myfile" />
<br/>
<input type="submit" />
</form>
</body></html>"""

    def POST(self):
        x = web.input(myfile={})
        web.debug(x['myfile'].value) # This is the file contents
        web.debug(x['myfile'].filename) # This is the filename
        web.redirect('/upload')


app = web.application(urls, globals())

if __name__ == "__main__":
    app.run()

Hang ups

A couple of things to watch out for:

[edit][history][backlinks] last modified February 20