Image filesize validator for dexterity content types in Plone¶
When using Plone 4.3 with plone.app.contenttypes 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 validators.py
in your package.
# -*- coding: utf-8 -*-
from plone.namedfile.interfaces import INamedBlobImageField
# from plone.app.contenttypes.interfaces 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)")
validator.WidgetValidatorDiscriminators(ImageFileSizeValidator,
# context=IImage,
field=INamedBlobImageField)
Now let’s register the new validator by adding following line to
configure.zcml
file.
<configure
xmlns="http://namespaces.zope.org/zope"
i18n_domain="example.package">
...
<!-- Register the z3c.form validator -->
<adapter factory=".validators.ImageFileSizeValidator" />
...
</configure>
So that’s it kids. If you want to register the adapter for Images only - and
you’re using plone.app.contenttypes, you could uncomment the additional
context=IImage
part.