在Symfony中,我可以使用以下方法接受MIME类型:
/**
* @Assert\File( maxSize="10M", mimeTypes={"application/pdf", "image/png"} )
*/
public $file;
但是如何从该列表中排除某些内容?比方说,我想允许除PHP文件之外的所有上传?
你可以通过断言实现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)在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上运行正常。
[]中