wiki:StoringAndRetrievingFilesFromDatabase
Warning: Can't synchronize with repository "(default)" (Unsupported version control system "svn": No module named svn). Look in the Trac log for more information.

Version 1 (modified by godoy, 13 years ago) (diff)

--

One common thing is storing files inside your database. This is usually done with image files, so this is what I'm going to show you here. You can adapt it to your needs. Complementary fields -- such as alternate_text, mimetype, etc. -- can be added at will.

The form:

        form = widgets.TableForm(fields = [
            widgets.FileField(
            name = 'image',
            label = _('Some picture'),
            validator = validators.FieldStorageUploadConverter())
           ])

Saving the image to the database:

    @expose()
    @validate(validators = {
        'image': validators.FieldStorageUploadConverter()
        })
    def save(self, image):
        image = model.Image(
            fileName = image.filename,
            image = image.file.read(),
        )
        return dict(image_id = image.id)

Retrieving the image from the database:

    @turbogears.expose(content_type = "image/jpg")
    def show_image(self, image_id):
        # "model.Image.q.image is where the image is stored
        return model.Image.get(image_id).image