Search code examples
symfonymime-typesassert

File upload: How to exclude a MIME type using asserts?


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 that list? Let's say, I want to allow all uploads except for PHP files?


Solution

  • You could implement a Callback constraint via an assert. One advantage of this method is you can apply the error message to any field (or fields) 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);
            }
        }
    }