在Symfony中,我可以使用以下方式接受MIME类型:
/**
* @Assert\File( maxSize="10M", mimeTypes={"application/pdf", "image/png"} )
*/
public $file;
但是如何从该列表中排除某些内容?比方说,我想允许除PHP文件以外的所有上传文件?
答案 0 :(得分:5)
您可以通过断言实现Callback constraint。此方法的一个优点是您可以将错误消息应用于表单中的任何字段(或字段)。
use Symfony\Component\Validator\ExecutionContext;
/**
* @ORM\Entity()
* @Assert\Callback(methods={"validateFile"})
*/
class MyEntity
{
public function validateFile(ExecutionContext $context)
{
$path = $context->getPropertyPath();
if (/* $this->file is not in allowed mimeTypes ... */) {
$context->setPropertyPath($path . '.file');
$context->addViolation("Invalid file mimetype", array(), null);
}
}
}
答案 1 :(得分:3)
您不需要创建任何回调来执行此操作。请确保:
1)在app / config / config.yml中将enable_annotations参数设置为true:
# app/config/config.yml
framework:
validation: { enable_annotations: true }
2)在您的实体文件中正确包含验证约束。
// YourEntity.php
use Symfony\Component\Validator\Constraints as Assert;
3)正确使用注释。例如:
// YourEntity.php
/**
* @Assert\File(
* maxSize="5242880",
* mimeTypes = {
* "image/png",
* "image/jpeg",
* "image/jpg",
* "image/gif",
* "application/pdf",
* "application/x-pdf"
* }
* )
*/
private $arquivo;
以上代码在我的Symfony 2.3.9上正常运行。
[]中