This is quite simple. HTML has a form input element of type "file" used to select the file. The form element looks like this
<input type="file" name="upload_file"/>The "name" is the variable name that TurboGears will pass into the controller function.
There are several ways to send a form to the server. File uploads must be sent using the "multipart/form-data" encoding, which is not the default. Here's an example form
<form action="http://localhost:8080/do_upload" method="POST" enctype="multipart/form-data"> filename: <input type="file" name="upload_file"/><br /> <input type="submit" value="Upload"/> </form>The form will be POSTed to the url "do_upload" and encoded with the right content-type. There are two form elements, one of type "file" and the other of type "submit". The "file" input will send the upload file as the form variable "upload_file".
The "upload_file" variable will reference a FieldStorage object. It's most important attribute is 'file', which contains the text of the uploaded document. Another possibly useful attribute is 'filename', which is the name from the server. People sometimes use this to help figure out the file type, by looking at the extension.
Here's an example controller showing this in action
@expose() def do_upload(self, upload_file): return ("You sent %r, which contains %d bytes" % (upload_file.filename, len(upload_file.file.read())))
When I tried it on a file I got:
You sent 'cv.txt', which contains 3315 bytes
To upload two files, use two "file" input elements.
Copyright © 2001-2013 Andrew Dalke Scientific AB