dsxd62219570
2017-01-12 10:51
浏览 53
已采纳

Symfony - 多个文件上传时不允许序列化

I have a form with a multiple upload field, but when I try to upload multiple files (or even if it's only one), it shows me the next error:

Exception in ArrayType.php line 45: Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed

The multiple upload field refeers to a property 'images', that it is an array.

/**
 * @var array
 * @ORM\Column(name="images", type="array", nullable=true)
 */
protected $images;

/**
 * Set images
 *
 * @param array $images
 * @return Artist
 */
public function setImages($images)
{
    $this->images = $images;

    return $this;
}

/**
 * Get images
 *
 * @return array 
 */
public function getImages()
{
    return $this->images;
}

In the twig I use this:

{{ form_label(form.images) }}
<br>
{{ form_errors(form.images) }}
{{ form_widget(form.images) }}
<br>

The action that I use for the form:

public function editAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager(); 

        $user = $this->getUser();
        $artist = $em->getRepository('CASUsuariosBundle:Artist')->find($user);

        if (!is_object($user) || !is_object($artist) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        $avatar1 = $artist->getAvatar();
        $cover1 = $artist->getCoverPhoto();
        $images1 = $artist->getImages();

        $form = $this->createForm(ArtistProfileType::class, $artist);
        $form->setData($artist);

        $form->handleRequest($request);

        if ($form->isValid()) {

            /** @var Symfony\Component\HttpFoundation\File\UploadedFile $avatar */
            $avatar = $artist->getAvatar();
            /** @var Symfony\Component\HttpFoundation\File\UploadedFile $cover */
            $cover = $artist->getCoverPhoto();
            /** @var Symfony\Component\HttpFoundation\File\UploadedFile $images */
            $images = $artist->getImages();


            if( $avatar === null )
            {

                $artist->setAvatar($avatar1);
            }
            else
            {

                $avatarName = md5(uniqid()).'.'.$avatar->guessExtension();

                $avDir = $this->container->getparameter('kernel.root_dir').'/../web/user/avatars';
                $avatar->move($avDir, $avatarName);
                $artist->setAvatar($avatarName);

            }

            if( $cover === null ) {

                $artist->setCoverPhoto($cover1);

            }
            else{

                /** @var Symfony\Component\HttpFoundation\File\UploadedFile $cover */
                $cover = $artist->getCoverPhoto();

                $coverName = md5(uniqid()).'.'.$cover->guessExtension();

                $coDir = $this->container->getparameter('kernel.root_dir').'/../web/user/covers';                
                $cover->move($coDir, $coverName);                
                $artist->setCoverPhoto($coverName);

            }

            $em->persist($artist);
            $em->flush();

            $url = $this->generateUrl('show_artist');
            $response = new RedirectResponse($url);
            return $response;
        }

        return $this->render('CASUsuariosBundle:Profile:edit_profile_artist.html.twig', array(
            'form' => $form->createView()
        ));
    }

And the formType:

public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder->add('categories', EntityType::class, array(
            'label' => 'Categoria',
            'class' => 'CASEventBundle:Category',
            'choice_label' => 'name',
            'multiple' => true
            ));
        $builder->add('subcategories', EntityType::class, array(
            'label' => 'Subcategorias',
            'class' => 'CASEventBundle:Subcategory',
            'choice_label' => 'name',
            'multiple' => true,
            'expanded' => true
            ));
        $builder->add('short_description', null, array('label' => 'Descripción corta'));
        $builder->add('description', null, array('label' => 'Descripción'));
        $builder->add('provinces', EntityType::class, array(
            'label' => 'Provincia',
            'class' => 'CASEventBundle:Province',
            'choice_label' => 'name',
            'required' => false,
            'multiple' => true,
            'expanded' => true
            ));
        $builder->add('city', null, array('label' => 'Ciudad'));
        $builder->add('avatar', FileType::class, array(
            "label" => "Imagen de perfil:",
            'required' => false,
            "data_class" => null
        ));
        $builder->add('cover_photo', FileType::class, array('required' => false, 
            'label' => 'Imagen de portada',
            'required' => false,
            'data_class' => null));
        $builder->add('images', FileType::class, array(
            'multiple' => true,
            'required' => false,
            "data_class" => null,
            'label' => 'Imagenes'
        ));
        $builder->add('members', null, array('required' => false, 'label' => 'Nº de miembros'));
        $builder->add('oficial_web', null, array('required' => false, 'label' => 'Página web'));
        $builder->add('facebook', null, array('required' => false));
        $builder->add('youtube', CollectionType::class, array(
            'required' => false,
            'allow_add' => true,
            'allow_delete' => true));
        $builder->add('soundcloud', CollectionType::class, array(
            'prototype' => true,
            'required' => false,
            'allow_add' => true,
            'allow_delete' => true));

    }

Sorry if my english is not very well. I'm learning it.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • donglu953744 2017-01-12 11:07
    已采纳

    When you submit your form you have an array of UploadedFile objects in you $images property. What I suggest is to map over that collection and perform saving that files similar to avatar and cover. Here an example of code:

    if ($images) {
        $imgDir = $this->container->getparameter('kernel.root_dir').'/../web/user/images';
        $artist->setImages(array_map(function ($img) use ($imgDir) {
            $imgName = md5(uniqid()).'.'.$img->guessExtension();
            $img->move($imgDir, $imgName);
    
            return $imgName;
        }, $images));
    }
    
    $em->persist($artist);
    $em->flush();
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题