How to use mimeType Assert with VichUploader?

TMichel picture TMichel · Dec 1, 2015 · Viewed 10.7k times · Source

This assert is passing Symfony's form validation when uploading any file with VichUploaderBundle:

/**
 * @Vich\UploadableField(mapping="product_media", fileNameProperty="path")
 * @Assert\File(
 *     mimeTypes = {"image/jpeg", "image/gif", "image/png", "video/mp4", "video/quicktime", "video/avi"},
 *     mimeTypesMessage = "Wrong file type (jpg,gif,png,mp4,mov,avi)"
 * )
 * @var File $pathFile
 */
protected $pathFile;

I cannot see what the problem is with the assert. How can I validate file types with VichUploader?

Answer

Mikhail Prosalov picture Mikhail Prosalov · Dec 15, 2015

You can use validation callback to solve this issue.

/**
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Repository\EntityRepository")
 * @ORM\Table(name="entity")
 * @Assert\Callback(methods={"validate"})
 * @Vich\Uploadable
 */
class Entity
{
    /**
     * @Assert\File(maxSize="10M")
     * @Vich\UploadableField(mapping="files", fileNameProperty="fileName")
     *
     * @var File $file
     */
    protected $file;

    /**
     * @ORM\Column(type="string", length=255, name="file_name", nullable=true)
     *
     * @var string $fileName
     */
    protected $fileName;

...

    /**
     * @param ExecutionContextInterface $context
     */
    public function validate(ExecutionContextInterface $context)
    {
        if (! in_array($this->file->getMimeType(), array(
            'image/jpeg',
            'image/gif',
            'image/png',
            'video/mp4',
            'video/quicktime',
            'video/avi',
        ))) {
            $context
                ->buildViolation('Wrong file type (jpg,gif,png,mp4,mov,avi)')
                ->atPath('fileName')
                ->addViolation()
            ;
        }
    }
}