【问题标题】:symfony2 image type constraint validationsymfony2 图像类型约束验证
【发布时间】:2014-03-05 18:08:07
【问题描述】:

我知道上传文件的首选方式是通过书中解释的 Doctrine,但我需要将图像数据保存在 xml 文件中,我也喜欢约束验证器。无需为它们编写太多代码。无论如何,我被困在图像约束上,我不知道我是否以正确的方式做所有事情。

我的 validator.yml 如下...

Frizer\AdminBundle\Entity\UploadedImage:
    properties:
        image:
            - Image:
                 notFoundMessage: Image not uploaded
                 uploadErrorMessage: The image could not upload. Try again
                 uploadIniSizeErrorMessage: Image has to  have more that 5M
                 mimeTypes: [image/jpeg, image/jpg, image/png]
                 mimeTypesMessage: Image has to be either jpg, jpeg or png format
                 minWidth: 500
                 minHeight: 500
                 minWidthMessage: Image has to be 500/500 px 
                 minHeightMessage: Image has to be 500/500px
                 maxSize: 5M
                 maxSizeMessage: Image has to have more than 5M

validate() 方法接受一个 UploadedImage 对象,该对象具有 $image 属性和具有 File 类型属性的该属性的 setter 方法。构造函数如下...

    $uploadedImage = new UploadedImage();

    $validator = $this->get('validator');
    $errors = $validator->validate($uploadedImage);

    var_dump($errors);

如果我上传大于 5M 的图片,$errors 为空。如果我不上传任何东西,同样的事情。我通过有关如何在文件上传中使用约束的教程搜索了网络和堆栈溢出,但没有成功。谁能解释我做错了什么?

【问题讨论】:

    标签: php validation symfony


    【解决方案1】:

    从您如何创建新的 UploadedImage 实体并尝试立即对其进行验证来判断,我怀疑您没有正确处理表单数据。

    看看Symfony2 file upload step by step——它也概述了上传,但使用注释进行验证。

    您不必使用学说,因此您可以忽略任何@ORM 注释。您只需在请求完成之前输出您需要输出的任何内容。

    另外,我不确定它是否是如何粘贴的,但请检查您在validation.yml 中的缩进级别(notFoundMessage、uploadErrorMessage 等,缩进不正确)

    Frizer\AdminBundle\Entity\UploadedImage:
        properties:
            image:
                - Image:
                    notFoundMessage: Image not uploaded
                    ...
    

    【讨论】:

    • 但这就是书中所说的。制作一个映射对象,制作 validator.yml 并将该对象放入 validate() 方法中。就是这样。我是否必须在 UploadedImage 对象中添加一些其他代码,例如 mimeType 字段或上传的图像路径?目前,它只有 $image 属性和一个 setter 方法。另外,我编辑了意图。如果意图是问题,我认为这将是一个错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 2015-02-13
    • 1970-01-01
    • 2017-08-16
    • 2019-09-19
    • 2019-03-23
    相关资源
    最近更新 更多