[英]Symfony - easyadmin 4 filetype constraint on ImageField
How can I limit the ImageField
to only accept png and jpg?如何限制
ImageField
只接受 png 和 jpg?
This is my code, but the issue is that i can upload pdf or.exe as well.这是我的代码,但问题是我也可以上传 pdf or.exe。
I cannot find a way to add a constraint here.我找不到在这里添加约束的方法。
public function configureFields(string $pageName): iterable
{
return [
TextField::new('entryTitle'),
TextEditorField::new('entryText'),
AssociationField::new('entryCategory'),
ImageField::new('mainImage')
->setBasePath('uploads/images/Blog')
->setUploadDir('public/uploads/images/Blog')
->setUploadedFileNamePattern('[randomhash].[extension]')
->setHelp('Only .png and .jpg')
];
}
You should just add an @Assert\File
on your property.您应该只在您的财产上添加一个
@Assert\File
。
use Symfony\Component\Validator\Constraints as Assert;
/**
* @Assert\File(
* maxSize="5M",
* maxSizeMessage="File exceed limit of: {{limit}}.",
* mimeTypes = {"image/jpeg", "image/png"},
* mimeTypesMessage = "File must be a JPG or PNG."
* )
*/
private ?File $imageFile = null;
Or if you really want to set it up manually you could use setFormTypeOption
:或者,如果你真的想手动设置它,你可以使用
setFormTypeOption
:
ImageField::new('mainImage')
->setBasePath('uploads/images/Blog')
->setUploadDir('public/uploads/images/Blog')
->setUploadedFileNamePattern('[randomhash].[extension]')
->setHelp('Only .png and .jpg')
->setFormTypeOption('constraints', [
new File([
'maxSize' => '5M',
'mimeTypes' => [
'image/jpeg',
'image/png',
],
'mimeTypesMessage' => 'Please upload a valid image. '
])
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.