On 14 Jun 2007, at 20:33, Andrew wrote:

> New to TurboGears.  I just worked through the 20-minute wiki tutorial,
> and now I would like to extend it by adding file uploads and downloads
> to pages.  A quick search leads me to FileFields, but there's no
> example on how to use it.  I'm looking for sample code on how to use
> it, especially w.r.t. modifying controllers.py.  Any suggestions,
> pointers, or links?

Here's a very quick example.  I hope it helps.

This is the controller.py which should just work with a quickstarted  
project, but the templates will need to be modified as appropriate.

Cheers,
CM


######################################

from turbogears import controllers, expose, widgets, validators,  
validate
from file_fields.widgets.file_field import FileField, FileValidator

# ---- Constants ----

BUFFER_SIZE = 8192

# ---- Widgets / Forms ----

class MediaUploadFields(widgets.WidgetsList):
     title = widgets.TextField(
         label=_(u"File Title"),
     )
     mediafile = FileField(
         label=_(u"Video File"),
     )


# ---- Form Validators ----

class MediaUploadSchema(validators.Schema):
     title = validators.UnicodeString(max=256, strip=True),
     mediafile = FileValidator(not_empty=True)

# ---- Forms ----

upload_form = widgets.TableForm( fields=MediaUploadFields(),  
validator=MediaUploadSchema() )

# ---- Controllers ----

class Root(controllers.RootController):
     @expose(template=".templates.welcome")
     def index(self):
         return dict(
             upload_action = './upload',
             upload_form = upload_form,
             upload_submit_text = 'Upload Media',
             upload_value = dict(),
         )

     @expose('.templates.upload', format='xml', content_type="text/xml")
     @validate(form=upload_form)
     def upload(self, title=None, mediafile=None):

         # Copy the file somewhere useful
         fp = open('/tmp/uploaded_file', 'wb')
         buf = mediafile.file.read(BUFFER_SIZE)
         while buf:
             fp.write(buf)
             buf = mediafile.file.read(BUFFER_SIZE)
         fp.close()

         return dict(
             filename      = mediafile.name,
             filesize      = mediafile.size,
             md5           = mediafile.md5,
             mimetype      = mediafile.type,
         )



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"TurboGears" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/turbogears?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to