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

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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码