Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 579
insertusernamehere Avatar asked Aug 23 '12 08:08

insertusernamehere


2 Answers

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);
        }
    }
}
like image 104
lifo Avatar answered Oct 05 '22 12:10

lifo


You don't need to create any callback to do this. Just make sure:

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

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

2) Include properly the validation constraints on your entity file.

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

3) Use the annotation properly. 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 is working fine on my Symfony 2.3.9.

[]s

like image 29
brunoric Avatar answered Oct 05 '22 11:10

brunoric