symfony - 如何在 Symfony 中同时使用 Assert\File 和 Assert\Image?

标签 symfony sonata-admin

我正在尝试通过两个条件验证文件上传:

  1. Only allowed to upload image file or PDF file

  2. Max width with Image file is 160px and no requirement with PDF file

我使用了 Symfony 的“约束”,但是当我上传 PDF 文件时,它说

This file is not a valid image.

因为我同时使用了Assert\Image和Assert\File,所以它会先检查文件是否是图像。

但是我想要的是当我上传文件时,它会首先检查Assert\File。如果是图像,则会检查 Assert\Image。我该怎么办?

这是我在实体的代码:

   /**
     * @Vich\UploadableField(mapping="ad", fileNameProperty="imageFile")
     * @var File
     * @Assert\File(
     *     mimeTypes = {"application/pdf", "application/x-pdf", "image/png", "image/jpeg", "image/svg+xml"},
     *     mimeTypesMessage = "You can only be allowed to upload Image file or PDF file"
     * )
     * @Assert\Image(
     *     maxWidth = 160
     * )
     */
    private $image;

最佳答案

你可以这样做:

#[Assert\AtLeastOneOf(
    constraints: [
        new Assert\File(extensions: ['pdf']),
        new Assert\Sequentially(
            [
                new Assert\File(extensions: ['jpg', 'jpeg','png','svg']),
                new Assert\Image(maxWidth: 160)
             ]
        ),
    ]
)]
public UploadedFile $file;

关于symfony - 如何在 Symfony 中同时使用 Assert\File 和 Assert\Image?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56554237/

相关文章:

forms - symfony2 表单中找不到实体错误

json - Symfony2实现PATCH方法来更新用户字段

php - Symfony2 chain_provider in_memory 用户登录 "bad credentials"

php - Symfony 2 Sonata Admin Bundle 的表演 Action 不起作用

sonata-admin - Sonata Admin 中的仪表板 Controller 设置

symfony - sonata_type_collection 字段仅适用于现有的父对象

symfony - 如何在symfony2的 View 中获取 session 变量

symfony - 教义 createNativeQuery 不返回结果

symfony - 在 SonataAdmin ListView 中显示名称而不是数据库值

php - Sonata - 如何创建动态属性过滤器?