我正在尝试通过两个条件验证文件上传:
Only allowed to upload image file or PDF file
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/