ins*_*ere 9 assert symfony mime-types
在Symfony中,我可以使用以下方法接受MIME类型:
/**
* @Assert\File( maxSize="10M", mimeTypes={"application/pdf", "image/png"} )
*/
public $file;
Run Code Online (Sandbox Code Playgroud)
但是如何从该列表中排除某些内容?比方说,我想允许除PHP文件之外的所有上传?
您可以通过断言实现Callback约束.此方法的一个优点是您可以将错误消息应用于表单中的任何字段(或多个字段).
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
您无需创建任何回调即可执行此操作。只要确保:
1)在您的app / config / config.yml中将enable_annotations参数设置为true:
# app/config/config.yml
framework:
validation: { enable_annotations: true }
Run Code Online (Sandbox Code Playgroud)
2)在您的实体文件中正确包含验证约束。
// YourEntity.php
use Symfony\Component\Validator\Constraints as Assert;
Run Code Online (Sandbox Code Playgroud)
3)正确使用注释。例:
// YourEntity.php
/**
* @Assert\File(
* maxSize="5242880",
* mimeTypes = {
* "image/png",
* "image/jpeg",
* "image/jpg",
* "image/gif",
* "application/pdf",
* "application/x-pdf"
* }
* )
*/
private $arquivo;
Run Code Online (Sandbox Code Playgroud)
上面的代码在我的Symfony 2.3.9上运行良好。
[]秒
| 归档时间: |
|
| 查看次数: |
14438 次 |
| 最近记录: |