File upload: how to exclude MIME type using assertions?

In Symfony, I can accept MIME types using:

/** * @Assert\File( maxSize="10M", mimeTypes={"application/pdf", "image/png"} ) */ public $file; 

But how can I exclude something from this list? Say I want to allow all downloads except PHP files?

+7
source share
2 answers

You can implement a callback restriction with the assert command. One of the advantages of this method is that you can apply an error message to any field (s) in your form.

 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); } } } 
+4
source

You do not need to create a callback for this. Just make sure:

1) Set the enable_annotations parameter as true in your /config/config.yml application:

 # app/config/config.yml framework: validation: { enable_annotations: true } 

2) Include the correct validation restrictions on the entity file.

 // YourEntity.php use Symfony\Component\Validator\Constraints as Assert; 

3) Use annotation correctly. Example:

 // YourEntity.php /** * @Assert\File( * maxSize="5242880", * mimeTypes = { * "image/png", * "image/jpeg", * "image/jpg", * "image/gif", * "application/pdf", * "application/x-pdf" * } * ) */ private $arquivo; 

The above code works fine on my Symfony 2.3.9.

[] S

+4
source

All Articles