How to restrict image file extension on Plone?

时间秒杀一切 提交于 2019-12-08 01:30:27

问题


I have a Plone application in which I can upload images, which are ATImages. I want to validate the extension file (mainly to forbid pdf files). There are created with a url call like http://blablba.com/createObject?type_name=Image I have tried setting the /content_type_registry with file extensions associated with images, with no success (pdf upload still work)

I guess I could write a new class extending ATImages, create a form with a validator, but it looks a little bit complicated and it seemed that some settings on content_type registry would be enough (or elsewhere).

How would you do that ? (forbid pdf ?)

thx


回答1:


We had a similar problem.

Archetypes fires several events during its magic, amongst others a "post validation event" (IObjectPostValidation). This way we added a check for the content-type.

subscriber (zcml):

<subscriber provides="Products.Archetypes.interfaces.IObjectPostValidation"
            factory=".subscribers.ImageFieldContentValidator" />

quick and dirty implementation:

from Products.Archetypes.interfaces.field import IImageField
from plone.app.blob.interfaces import IBlobImageField
from Products.Archetypes.interfaces import IObjectPostValidation
from zope.interface import implements
from zope.component import adapts
# import your message factory as _


ALLOWED_IMAGETYPES = ['image/png',
                      'image/jpeg',
                      'image/gif',
                      'image/pjpeg',
                      'image/x-png']


class ImageFieldContentValidator(object):
    """Validate that the ImageField really contains a Imagefile.
    Show a Errormessage if it doesn't.
    """
    implements(IObjectPostValidation)
    adapts(IBaseObject)

    img_interfaces = [IBlobImageField, IImageField]

    msg = _(u"error_not_image",
            default="The File you wanted to upload is no image")

    def __init__(self, context):
        self.context = context

    def __call__(self, request):
        for fieldname in self.context.Schema().keys():
            field = self.context.getField(fieldname)
            if True in [img_interface.providedBy(field) \
                            for img_interface in self.img_interfaces]:
                item = request.get(fieldname + '_file', None)
                if item:
                    header = item.headers
                    ct = header.get('content-type')
                    if ct in ALLOWED_IMAGETYPES:
                        return
                    else:
                        return {fieldname: self.msg}


来源:https://stackoverflow.com/questions/15951825/how-to-restrict-image-file-extension-on-plone

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!