Image filesize validator for dexterity content types in Plone

When using Plone 4.3 with you might want to limit max filesize for images by implementing a custom z3c.form validator. In ATCT we were able to limit max image filesize by overwriting ATCT config file or setting in portal_atct tool.

Using webserver

The simplest way to achieve a max-upload size is to just limit client_max_body_size in nginx webserver (or simliar in apache).

But my current solution is really different. It creates a validator for a special fieldtype, in our special case a INamedBlobImageField.

Using validator

First, create a new file in your package.

# -*- coding: utf-8 -*-
from plone.namedfile.interfaces import INamedBlobImageField
# from import IImage
from zope.interface import Invalid
from z3c.form import validator

# 1 MB size limit
MAXSIZE = 1024 * 1024

class ImageFileSizeValidator(validator.FileUploadValidator):

    def validate(self, value):
        super(ImageFileSizeValidator, self).validate(value)

        if value.getSize() > MAXSIZE:
            raise Invalid("Image is too large (to many bytes)")

#                                        context=IImage,

Now let’s register the new validator by adding following line to configure.zcml file.


    <!-- Register the z3c.form validator -->
    <adapter factory=".validators.ImageFileSizeValidator" />


So that’s it kids. If you want to register the adapter for Images only - and you’re using, you could uncomment the additional context=IImage part.


comments powered by Disqus