Kévin Duguay
Kévin Duguay

Reputation: 761

How to check if a uploaded file is a pdf in Symfony 2

I'm working on the validation of one of my form and I need to check that the uploaded file is a pdf. I tried using a File constraint in my form, but it still let's me pass something that's not a pdf (a .txt for exemple).

Am I doing it wrong or should a use an other method to do that?

My form:

<?php

namespace AdminBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\File;

Class FormUpdateCV extends AbstractType
{
    public function buildForm(FormBuilderInterface $constructeur, array $options)
    {
        $format_fichier=new File(array(
                                'mimeTypes'=>'application/pdf',
                                'mimeTypesMessage'=>'Le fichier doit être un pdf'
                            ));

        $constructeur
        ->add('CV','file',array('label'=>'C.V.:', 'constraints'=>array($format_fichier)))
        ->add('mettreAJour','submit',array('label'=>'Mettre à jour'));
    }

    public function getName()
    {

        return 'update_CV';

    }
}

Upvotes: 2

Views: 1755

Answers (2)

K&#233;vin Duguay
K&#233;vin Duguay

Reputation: 761

After trying some stuff, it seems like my previous condition does work. It's just that if I had, for exemple, a .pdf file and choose to change the extension to .txt, it still recognize it as a .pdf, but it still change the extention in my controller, so it's o.k. On the other side, if I change a .txt for a .pdf it still recognize the file as .txt, which is good since the file would read wright anyway.

Upvotes: 0

zilongqiu
zilongqiu

Reputation: 846

You can add constraint directly in the entity. What do you think about this solution.

// src/Acme/BlogBundle/Entity/Author.php
namespace Acme\BlogBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    /**
     * @Assert\File(
     *     maxSize = "1024k",
     *     mimeTypes = {"application/pdf", "application/x-pdf"},
     *     mimeTypesMessage = "Please upload a valid PDF"
     * )
     */
    protected $bioFile;
}

Upvotes: 1

Related Questions