【问题标题】:symfony 4 - form constraint - image not workingsymfony 4 - 形式约束 - 图像不工作
【发布时间】:2019-11-12 22:41:55
【问题描述】:

我的代码生成器(相关部分)中有以下代码:

use Symfony\Component\Validator\Constraints\Image;
..................................................
$builder->add('image', FileType::class, [
    'required' => false,
    'constraints' => [
         new Image([
             'maxSize' => '2048k'
         ])
    ]
])

表单创建正确,到目前为止一切正常。现在,在提交时,在控制器中我有以下代码:

$form = $this->createForm(OrderReviewType::class);
$form->handleRequest($request);


if ($form->isSubmitted() && $form->isValid()) {
    dd($request->files);
}

例如,当我上传一个 html 文件时,我希望验证失败(约束是图像)。而是验证表单。转储如下:

FileController.php on line 43:
FileBag^ {#15 ▼
  #parameters: array:1 [▼
    "order_review" => array:1 [▼
      "image" => UploadedFile^ {#16 ▼
        -test: false
        -originalName: "test.html"
        -mimeType: "text/html"
        -error: 0
        path: "/tmp"
        filename: "phpOPra8g"
        basename: "phpOPra8g"
        pathname: "/tmp/phpOPra8g"
        extension: ""
        realPath: "/tmp/phpOPra8g"
        aTime: 2019-07-02 12:51:24
        mTime: 2019-07-02 12:51:24
        cTime: 2019-07-02 12:51:24
        inode: 17041021
        size: 678
        perms: 0100600
        owner: 1000
        group: 1000
        type: "file"
        writable: true
        readable: true
        executable: false
        file: true
        dir: false
        link: false
      }
    ]
  ]
}

知道为什么约束不起作用吗?没有错误发生。

【问题讨论】:

  • 想解释一下-1吗?

标签: php forms symfony validation symfony4


【解决方案1】:

我去过Symfony Documentation for Image Constraint,还没有看到maxSize Option。

它还指定为确保检查图像是否有效以及一定的尺寸,您应该使用:minWidth、maxWidth、minHeight、maxHeight 选项。

我只是在这里浏览 Symfony 文档,但你确定你使用了正确的选项来限制你的图像吗?

【讨论】:

  • 图像约束扩展了具有 maxSize 的文件约束。来自文档: Image 约束的工作方式与 File 约束完全相同,只是它的 mimeTypes 和 mimeTypesMessage 选项会自动设置为专门用于图像文件。此外,它具有选项,因此您可以根据图像的宽度和高度进行验证。有关此约束的大部分文档,请参阅文件约束。并从代码中:class Image extends File, protected $maxSize;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-28
  • 2015-06-18
  • 2023-01-16
  • 2019-09-22
  • 2018-06-24
  • 1970-01-01
  • 2020-07-30
相关资源
最近更新 更多