IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Symfony PHP Discussion :

Multiple uploads avec VichUploader


Sujet :

Symfony PHP

  1. #1
    Membre éprouvé
    Homme Profil pro
    Inscrit en
    Mai 2004
    Messages
    803
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Mai 2004
    Messages : 803
    Par défaut Multiple uploads avec VichUploader
    Bonjour,

    Savez-vous s'il est possible d'envoyer, via un seul formulaire, un nombre indéfini de fichiers avec VichUploader (un annonce contenant plusieurs photos)? J'ai trouvé de la documentation pour un seul fichier mais pas pour plusieurs.

    Merci d'avance pour votre réponse.

  2. #2
    Membre éprouvé
    Homme Profil pro
    Inscrit en
    Mai 2004
    Messages
    803
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations forums :
    Inscription : Mai 2004
    Messages : 803
    Par défaut
    J'ai une entité Advert qui peut être liée à plusieurs entités Image. Mon but est d'avoir la possibilité, lorsqu'on encode une annonce, de pouvoir y joindre, dans un même formulaire, plusieurs photos. Pour cela, j'utilise vichUploader, LippImagine et le webpack Encore.

    Pour se faire voici mes différentes sources :

    Mon entité Advert :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    <?php
     
    namespace App\Entity;
     
    use Webmozart\Assert\Assert;
    use Doctrine\ORM\Mapping as ORM;
    use Doctrine\Common\Collections\Collection;
    use Doctrine\Common\Collections\ArrayCollection;
     
    /**
     * @ORM\Entity(repositoryClass="App\Repository\AdvertRepository")
     */
    class Advert
    {
        /**
         * @ORM\Id()
         * @ORM\GeneratedValue()
         * @ORM\Column(type="integer")
         */
        private $id;
     
        /**
         * @ORM\Column(type="text")
         */
        private $description;
     
        /**
         * @ORM\OneToOne(targetEntity="App\Entity\Vehicle", inversedBy="advert", cascade={"persist", "remove"})
         * @ORM\JoinColumn(nullable=false)
         */
        private $vehicle;
     
        /**
         * @ORM\OneToMany(targetEntity="App\Entity\Image", mappedBy="advert", orphanRemoval=true)
         */
        private $images;
     
        public function __construct()
        {
            $this->images = new ArrayCollection();
        }
     
        public function getId(): ?int
        {
            return $this->id;
        }
     
        public function getDescription(): ?string
        {
            return $this->description;
        }
     
        public function setDescription(string $description): self
        {
            $this->description = $description;
     
            return $this;
        }
     
        public function getVehicle(): ?Vehicle
        {
            return $this->vehicle;
        }
     
        public function setVehicle(Vehicle $vehicle): self
        {
            $this->vehicle = $vehicle;
     
            return $this;
        }
     
        /**
         * @return Collection|Image[]
         */
        public function getImages(): Collection
        {
            return $this->images;
        }
     
        public function addImage(Image $iamge): self
        {
            if (!$this->images->contains($image)) {
                $this->images[] = $image;
                $image->setAdvert($this);
            }
     
            return $this;
        }
     
        public function removeImage(Image $image): self
        {
            if ($this->images->contains($image)) {
                $this->images->removeElement($image);
                // set the owning side to null (unless already changed)
                if ($iamge->getAdvert() === $this) {
                    $image->setAdvert(null);
                }
            }
     
            return $this;
        }
    }
    Mon entité Image :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    <?php
     
    // src/AppBundle/Entity/Image.php
     
    namespace App\Entity;
     
    use Doctrine\ORM\Mapping as ORM;
    use Symfony\Component\HttpFoundation\File\File;
    use Vich\UploaderBundle\Mapping\Annotation as Vich;
    use Symfony\Component\Validator\Constraints as Assert;
    use App\Validator\Constraints as AppAssert;
     
     
    /**
     * @Vich\Uploadable
     * @ORM\Entity(repositoryClass="AppBundle\Repository\ImageRepository")
     * @AppAssert\Image
     */
    class Image
    {
     
        /**
         * @var int
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;
     
        /**
         * @ORM\Column(type="string", length=255)
         * @Assert\Length(max=255)
         * @var string
         */
        private $image;
     
        /**
         * @Vich\UploadableField(mapping="images", fileNameProperty="image")
         * @Assert\File(
         * maxSize="1000k",
         * maxSizeMessage="Le fichier excède 1000Ko.",
         * mimeTypes={"image/png", "image/jpeg", "image/jpg", "image/svg+xml", "image/gif"},
         * mimeTypesMessage= "formats autorisés: png, jpeg, jpg, svg, gif"
         * )
         * @var File
         */
        private $imageFile;
     
        /**
         * @ORM\Column(type="datetime")
         * @var \DateTime
         */
        private $updatedAt;
     
        /**
        * @var string
        *
         * @ORM\Column(type="string", length=255, nullable=true)
        */
        private $tmpFile;
     
        /**
         * @ORM\ManyToOne(targetEntity="App\Entity\Advert", inversedBy="photos")
         * @ORM\JoinColumn(nullable=false)
         */
        private $advert;
     
        public function __toString(){
        return (string) $this->image;
        }
     
        /**
         * Get id
         *
         * @return int
         */
        public function getId()
        {
            return $this->id;
        }
     
        public function setImageFile(File $image = null)
        {
            $this->imageFile = $image;
     
            // VERY IMPORTANT:
            // It is required that at least one field changes if you are using Doctrine,
            // otherwise the event listeners won't be called and the file is lost
            if ($image) {
                // if 'updatedAt' is not defined in your entity, use another property
                $this->updatedAt = new \DateTime('now');
            }
        }
     
        public function getImageFile()
        {
            return $this->imageFile;
        }
     
        public function setImage($image)
        {
            $this->image = $image;
        }
     
        public function getImage()
        {
            return $this->image;
        }
     
        public function setUpdatedAt($updatedAt)
        {
            $this->updatedAt = $updatedAt;
        }
     
        public function getUpdatedAt(){
            return $this->updatedAt;
        }
     
        /*
        * Set tmpFile
        * @return Image
        */
        public function setTmpFile($tmpFile)
        {
            $this->tmpFile = $tmpFile;
            return $this;
        }
     
        /*
        * Get tmpFile
        * @return string
        */
        public function getTmpFile()
        {
            return $this->tmpFile;
        }
     
        public function getAdvert(): ?Advert
        {
            return $this->advert;
        }
     
        public function setAdvert(?Advert $advert): self
        {
            $this->advert = $advert;
     
            return $this;
        }    
     
        public function validate($protocol, Constraint $constraint)
        {
            if($protocol->getImageFile() === null && $protocol->getImage() === null && $protocol->getUpdatedAt() === null)
            {
                return $this->context
                    ->buildViolation($constraint->message)
                    ->atPath('imageFile')
                    ->addViolation()
                    ;
            }
        }
    }
    Ma classe Image dans le validateur :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    <?php
     
    //src/AppBundle/Validator/Constraints/Image.php
     
    namespace App\Validator\Constraints;
     
    use Symfony\Component\Validator\Constraint;
     
    /**
     * @Annotation
     */
    class Image extends Constraint
     
    {
        public $message = "L'image n'a pas été renseignée.";
     
        public function getTargets()
        {
            return self::CLASS_CONSTRAINT;
        }
    }
    Mon validateur :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <?php
     
    // src/AppBundle/Validator/Constraints/ImageValidator.php
     
    namespace App\Validator\Constraints;
     
    use Symfony\Component\Validator\Constraint;
    use Symfony\Component\Validator\ConstraintValidator;
     
    class ImageValidator extends ConstraintValidator
    {
        public function validate($protocol, Constraint $constraint)
        {
            if($protocol->getImageFile() === null && $protocol->getImage() === null && $protocol->getUpdatedAt() === null)
            {
                return $this->context
                    ->buildViolation($constraint->message)
                    ->atPath('imageFile')
                    ->addViolation()
                    ;
            }
        }
    }
    Mon extension Twig :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    <?php
    namespace App\Twig;
     
    use Liip\ImagineBundle\Imagine\Cache\CacheManager;
     
    class TwigExtension extends \Twig_Extension
    {
            private $imageDir;
            private $cacheManager;
     
        public function __construct(CacheManager $cacheManager, string $imageDir)
        {
            $this->imageDir = $imageDir;
            $this->cacheManager = $cacheManager;
        }
     
        public function getFilters(){
            return array(
                new \Twig_SimpleFilter('my_imagine_filter', array($this, 'myImagineFilter')),
            );
        }
     
        public function myImagineFilter($path, $filter, array $runtimeConfig = array(), $resolver = null)
        {
            $ext = pathinfo($path, PATHINFO_EXTENSION);
     
            if($ext === "svg")
            {
                 return $this->imageDir."/".basename($path);
            }
            else
            {
                return $this->cacheManager->getBrowserPath($path, $filter, $runtimeConfig, $resolver);
            }
     
        }
     
    }
    Mon formulaire pour Image :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    <?php
     
    namespace App\Form;
     
    use App\Entity\Image;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolver;
     
    class ImageType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('image', FileType::class, array('label' => 'Photo'))
                //->add('updatedAt')
                //->add('tmpFile')
                //->add('advert')
            ;
        }
     
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults([
                'data_class' => Image::class,
            ]);
        }
    }
    Mon formulaire pour Advert :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    <?php
     
    namespace App\Form;
     
    use App\Entity\Advert;
    use App\Form\VehicleType;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Vich\UploaderBundle\Form\Type\VichImageType;
    use Symfony\Component\OptionsResolver\OptionsResolver;
    use Symfony\Component\Form\Extension\Core\Type\CollectionType;
     
    class AdvertType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('description')
                ->add('vehicle', VehicleType::class)
                //->add('image', CollectionType::class, array('entry_type' => ImageType::class, 'entry_options' => array('label' => false), 'allow_add' => true, 'allow_add' => true,));
                ->add('image', VichImageType::class, array('entry_type' => ImageType::class, 'entry_options' => array('label' => false), 'allow_add' => true, 'allow_add' => true,))
            ;
        }
     
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults([
                'data_class' => Advert::class,
            ]);
        }
    }
    Mon template pour le formulaire Advert :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    {% extends "base.html.twig" %}
     
    {% form_theme formAdvert 'bootstrap_4_layout.html.twig' %}
     
    {% block body %}
     
        {% if editMode %}
     
            <h1>Modification de votre annonce</h1>
     
        {% else %}
     
            <h1>Création de votre annonce</h1>
     
        {% endif %}
     
        {{ form_start(formAdvert) }}
        {{ form_errors(formAdvert) }}
     
        <div>
            {{ form_label(formAdvert.description, 'Description', {'label_attr': {'class': 'foo'}}) }}
            {{ form_errors(formAdvert.description) }}
            {{ form_widget(formAdvert.description) }}
     
            {{ form_label(formAdvert.vehicle.manufactureDate, 'Date de construction du véhicule', {'label_attr': {'class': 'foo'}}) }}
            {{ form_errors(formAdvert.vehicle.manufactureDate) }}
            {{ form_widget(formAdvert.vehicle.manufactureDate.day, {'attr': {  'style': 'display:none'}}) }}
     
            {{ form_label(formAdvert.vehicle.mark.mark, 'Marque', {'label_attr': {'class': 'foo'}}) }}
            {{ form_errors(formAdvert.vehicle.mark.mark) }}
            {{ form_widget(formAdvert.vehicle.mark.mark) }}
     
            {{ form_label(formAdvert.vehicle.fuel.fuel, 'Carburant', {'label_attr': {'class': 'foo'}}) }}
            {{ form_errors(formAdvert.vehicle.fuel.fuel) }}
            {{ form_widget(formAdvert.vehicle.fuel.fuel) }}
     
            {{ form_label(formAdvert.vehicle.sort.sort, 'Type', {'label_attr': {'class': 'foo'}}) }}
            {{ form_errors(formAdvert.vehicle.sort.sort) }}
            {{ form_widget(formAdvert.vehicle.sort.sort) }}
     
            {{ form_label(formAdvert.vehicle.numberBeds, 'Nombre de couchages', {'label_attr': {'class': 'foo'}}) }}
            {{ form_errors(formAdvert.vehicle.numberBeds) }}
            {{ form_widget(formAdvert.vehicle.numberBeds) }}
        </div>
     
        <h3>Photos</h3>
        <ul class="images"data-prototype="{{ form_widget(formAdvert.images.vars.prototype)|e('html_attr') }}">
            {# iterate over each existing tag and render its only field: name #}
            {% for image in formAdvert.images %}
                <li>{{ form_row(form.image) }}</li>
            {% endfor %}
        </ul>
     
        <button type="submit" class="btn btn-success">
     
            {% if editMode %}
     
                Enregistrer les modifications
     
            {% else %}
     
                Ajouter l'annonce
     
            {% endif %}
     
        </button>
     
        {{ form_end(formAdvert) }}
     
        {% block javascripts %}
            {{ parent() }}
            {{ encore_entry_script_tags('addAdvert') }}
        {% endblock %}
     
    {% endblock body %}
    Mon fichier js lié au template qui permet d'ajouter des photos supplémentaires :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    var $collectionHolder ;    
     
    // setup an "add a photo" link
    var $addImageButton = $ ( '<button type="button" class="add_image_link">Ajouter une photo</button>' );
    var $newLinkLi = $ ( '<li></li>' ). append ( $addImageButton );
     
    jQuery ( document ). ready ( function () {
        // Get the ul that holds the collection of photos
        $collectionHolder = $ ( 'ul.images' );
     
        // add the "add a photo" anchor and li to the images ul
        $collectionHolder . append ( $newLinkLi );
     
        // count the current form inputs we have (e.g. 2), use that as the new
        // index when inserting a new item (e.g. 2)
        $collectionHolder . data ( 'index' , $collectionHolder . find ( ':input' ). length );
     
        $addPhotoButton . on ( 'click' , function ( e ) {
        // add a new image form (see next code block)
        addImageForm ( $collectionHolder , $newLinkLi );
        });
     
        function addImageForm ( $collectionHolder , $newLinkLi ) {
            // Get the data-prototype explained earlier
            var prototype = $collectionHolder . data ( 'prototype' );
     
            // get the new index
            var index = $collectionHolder . data ( 'index' );
     
            var newForm = prototype ;
            // You need this only if you didn't set 'label' => false in your tags field in TaskType
            // Replace '__name__label__' in the prototype's HTML to
            // instead be a number based on how many items we have
            // newForm = newForm.replace(/__name__label__/g, index);
     
            // Replace '__name__' in the prototype's HTML to
            // instead be a number based on how many items we have
            newForm = newForm . replace ( /__name__/g , index );
     
            // increase the index with one for the next item
            $collectionHolder . data ( 'index' , index + 1 );
     
            // Display the form in the page in an li, before the "Add a tag" link li
            var $newFormLi = $ ( '<li></li>' ). append ( newForm );
            $newLinkLi . before ( $newFormLi );
        }
    });
    Et enfin l'appel dans mon controller :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
        /**
         *  @Route("/motorhomes/newAdvert", name="motorhomes_createAdvert")
         *  @Route("/motorhomes/{id}/editAdvert", name="motorhomes_editAdvert")
         */
     
        public function advertForm(Advert $advert = null, Request $request, ObjectManager $manager){
     
            if (!$advert) {
                $advert = new Advert;
     
                $image1 = new Image();
                $image1->setAdvert($advert);
                $image2 = new Image();
                $image2->setAdvert($advert);           
     
                $form = $this->createForm(ImageType::class, $image);
                $form->handleRequest($request);
     
                /*$image1 = new Image();
                //$photo1->setImageName('photo1');
                $image1->setAdvert($advert);
                //$photo1->setUpdatedAt(new \DateTime());
                $advert->getImages()->add($photo1);
                $image2 = new Iùage();
                //$photo2->setImageName('photo2');
                $photo2->setAdvert($advert);
                //$photo1->setUpdatedAt(new \DateTime());
                $advert->getImages()->add($photo2);*/
            }
     
            //$form = $this->createForm(AdvertType::class, $advert);
     
            //$form->handleRequest($request);
     
            if ($form->isSubmitted() && $form->isValid()) {
                // $file stores the uploaded PDF file
                /** @var Symfony\Component\HttpFoundation\File\UploadedFile $file */
                $file = $advert->getImages();
     
                foreach ($file as $key => $value) {
                    $fileName = $this->generateUniqueFileName().'.'.$value->guessExtension();
     
                    // Move the file to the directory where images are stored
                    try {
                        $value->move(
                            $this->getParameter('images_directory'),
                            $fileName
                        );
                    } catch (FileException $e) {
                        // ... handle exception if something happens during file upload
                    } 
                }           
     
                $manager->persist($fuel);
                $manager->flush();        
     
                return $this->redirectToRoute('motorhomes_adverts');
            }
     
            return $this->render('motorhomes/createAdvert.html.twig', ['formAdvert' => $form->createView(), 'editMode' => $advert->getId() !== null]);        
        }
    Lorsque je tente de générer la page du formulaire d'encodage "http://127.0.0.1:8000/motorhomes/newAdvert", j'ai un time out :

    (1/1) FatalErrorException
    Error: Maximum execution time of 30 seconds exceeded

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. problème upload avec XMLHttpRequest
    Par alexmorel dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 17/12/2005, 17h36
  2. [Tomcat][Struts] Lenteur upload avec ie
    Par Yali dans le forum Tomcat et TomEE
    Réponses: 4
    Dernier message: 26/08/2005, 16h52
  3. Supprimer fichier uploader avec aspSmartUpload
    Par julio_097 dans le forum ASP
    Réponses: 2
    Dernier message: 11/08/2005, 16h27
  4. url d'une page asp ou upload avec get
    Par taupin dans le forum ASP
    Réponses: 18
    Dernier message: 22/08/2003, 14h25
  5. Erreurs IIS avec Multiples Frames avec xmlrad
    Par powerlog dans le forum XMLRAD
    Réponses: 4
    Dernier message: 01/07/2003, 13h15

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo