dongpao1873 2019-05-22 15:43
浏览 139

Symfony4不允许序列化'Symfony \ Component \ HttpFoundation \ File \ File'?

I've added an avatar image to my User class. When I wanted to render my edit form, I got this error

Serialization of 'Symfony\Component\HttpFoundation\File\File' is not allowed

I tried to solve the problem by implementing \Serializable in my User class according to Symfony Official Documentation. but didint work.

Here is my UserEntity, Artsite.php:

         <?php

          namespace App\Entity;

          use Doctrine\Common\Collections\ArrayCollection;
          use Doctrine\Common\Collections\Collection;
          use Doctrine\ORM\Mapping as ORM;
          use Symfony\Component\Security\Core\User\UserInterface;
          use 
          Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
          use Symfony\Component\Validator\Constraints as Assert;
          use Serializable;
          /**
          * 
        @ORM\Entity(repositoryClass="App\Repository\ArtisteRepository")
      *  @UniqueEntity(fields={"username"}, message="There is already 
     an account with this username")
      */
     class Artiste implements UserInterface, Serializable
    {
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string", length=255)
 */
private $NomPrenom;

/**
 * @ORM\Column(type="string", length=255)
 */
private $adresse;

/**
 * @ORM\Column(type="integer")
 */
private $numero1;

/**
 * @ORM\Column(type="integer", nullable=true)
 */
private $numero2;

/**
 * @ORM\Column(type="string", length=255)
 */
private $username;

/**
 * @ORM\Column(type="string", length=255)
 */
private $password;

 /**
 * @ORM\Column(type="string", nullable=true)
 * @Assert\File(mimeTypes={ "image/*" },mimeTypesMessage="C'est n'est pas une image")
 */
private $image;

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Produit", mappedBy="artiste_id")
 */
private $produits;

public function __construct()
{
    $this->produits = new ArrayCollection();
}


 public function getImage()
{
    return $this->image;
}

public function setImage($image)
{
    $this->image = $image;

    return $this;
}

public function getId(): ?int
{
    return $this->id;
}

public function getNomPrenom(): ?string
{
    return $this->NomPrenom;
}

public function setNomPrenom(string $NomPrenom): self
{
    $this->NomPrenom = $NomPrenom;

    return $this;
}

public function getAdresse(): ?string
{
    return $this->adresse;
}

public function setAdresse(string $adresse): self
{
    $this->adresse = $adresse;

    return $this;
}

public function getNumero1(): ?int
{
    return $this->numero1;
}

public function setNumero1(int $numero1): self
{
    $this->numero1 = $numero1;

    return $this;
}

public function getNumero2(): ?int
{
    return $this->numero2;
}

public function setNumero2(?int $numero2): self
{
    $this->numero2 = $numero2;

    return $this;
}

public function getUsername(): ?string
{
    return $this->username;
}

public function setUsername(string $username): self
{
    $this->username = $username;

    return $this;
}

public function getPassword(): ?string
{
    return $this->password;
}

public function setPassword(string $password): self
{
    $this->password = $password;

    return $this;
}

/**
 * @return Collection|Produit[]
 */
public function getProduits(): Collection
{
    return $this->produits;
}

public function addProduit(Produit $produit): self
{
    if (!$this->produits->contains($produit)) {
        $this->produits[] = $produit;
        $produit->setArtisteId($this);
    }

    return $this;
}

public function removeProduit(Produit $produit): self
{
    if ($this->produits->contains($produit)) {
        $this->produits->removeElement($produit);
        // set the owning side to null (unless already changed)
        if ($produit->getArtisteId() === $this) {
            $produit->setArtisteId(null);
        }
    }

    return $this;
}

public function eraseCredentials()
{
}
   public function getSalt()
{
}

 public function getRoles(): array
{
    $roles[] = 'ROLE_Etudiant';
    return array_unique($roles);
}


       /** @see \Serializable::serialize() */
         public function serialize()
       {   
    return serialize(array(
        $this->id,
        $this->image,
        $this->username,
        $this->password,
    ));
}

/** @see \Serializable::unserialize() */
public function unserialize($serialized)
{ 
    list (
        $this->id,
        $this->image,
        $this->username,
        $this->password,
    ) = unserialize($serialized, array('allowed_classes' => false));
}

} Here is my UserController.php

               <?php

      namespace App\Controller;

 use App\Entity\Artiste;
 use App\Form\ArtisteType;
 use App\Repository\ArtisteRepository;
 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
 use Symfony\Component\HttpFoundation\Request;
  use Symfony\Component\HttpFoundation\Response;
  use Symfony\Component\Routing\Annotation\Route;
  use 
  Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
     use 
 Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  use Symfony\Component\Security\Core\Security;
   use Symfony\Component\HttpFoundation\File\File;

   class ArtisteController extends AbstractController
  {
/**
 * @Route("/", name="artiste_index", methods={"GET"})
 */
public function index(ArtisteRepository $artisteRepository,Security $security)
{
    $user = $security->getUser();
    return $this->render('artiste/index.html.twig', [
        'client' =>$user
    ]);
}
/**
 * @Route("/login", name="artiste_login", methods={"GET","POST"})
 */
public function login(AuthenticationUtils $authenticationUtils)
{
    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();    
    // last username entered by the user
    $lastUsername = $authenticationUtils->getLastUsername();

    return $this->render('artiste/login.html.twig', [
        'last_username' => $lastUsername,
        'error'         => $error,
    ]); 
}

/**
 * @Route("/logout", name="artiste_logout")
 */
public function logout()
{

}

/**
 * @Route("/new", name="artiste_new", methods={"GET","POST"})
 */
public function new(Request $request,UserPasswordEncoderInterface $encoder): Response
{
    $artiste = new Artiste();
    $form = $this->createForm(ArtisteType::class, $artiste);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $hash=$encoder->encodePassword($artiste,$artiste->getPassword());
        $artiste->setPassword($hash);

        $file = $artiste->getImage();
        if($file=="")
            $artiste->setImage("default.jpg");
        else{
            $fileName = $this->generateUniqueFileName().'.'.$file->guessExtension();

            // Move the file to the directory where brochures are stored
            try {
                $file->move(
                    $this->getParameter('images_directory'),
                    $fileName
                );
            } catch (FileException $e) {
                // ... handle exception if something happens during file upload
            }

            $artiste->setImage($fileName);
    }

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($artiste);
        $entityManager->flush();

        return $this->redirectToRoute('artiste_login');
    }

    return $this->render('artiste/new.html.twig', [
        'artiste' => $artiste,
        'form' => $form->createView(),
    ]);
}
/**
 * @return string
 */
private function generateUniqueFileName()
{
    // md5() reduces the similarity of the file names generated by
    // uniqid(), which is based on timestamps
    return md5(uniqid());
}

/**
 * @Route("/profile", name="artiste_profile", methods={"GET"})
 */
public function show(Security $security)
{
    $user = $security->getUser();
    return $this->render('artiste/profile.html.twig', [
        'client' => $user,
    ]);
}

/**
 * @Route("/edit", name="artiste_edit", methods={"GET","POST"})
 */
public function edit(Request $request,Security $security,UserPasswordEncoderInterface $encoder)
{
    $artiste=$security->getUser();
    $artiste->setImage( new File($this->getParameter('images_directory').'/'.$artiste->getImage()));
    $form = $this->createForm(ArtisteType::class, $artiste);
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {

        $hash=$encoder->encodePassword($artiste,$artiste->getPassword());
        $artiste->setPassword($hash);
        $file = $artiste->getImage();
            $fileName = $this->generateUniqueFileName().'.'.$file->guessExtension();

            // Move the file to the directory where brochures are stored
            try {
                $file->move(
                    $this->getParameter('images_directory'),
                    $fileName
                );
            } catch (FileException $e) {
                // ... handle exception if something happens during file upload
            }

            $artiste->setImage($fileName);

        $this->getDoctrine()->getManager()->flush();

        return $this->redirectToRoute('artiste_profile', [
            'client' => $artiste,
        ]);
    }

    return $this->render('artiste/edit.html.twig', [
        'client' => $artiste,
        'form' => $form->createView(),
    ]);
}

Here is my UserForm, UserType.php

  <?php

  namespace App\Form;

  use App\Entity\Artiste;
  use Symfony\Component\Form\AbstractType;
  use Symfony\Component\Form\FormBuilderInterface;
  use Symfony\Component\OptionsResolver\OptionsResolver;
  use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  use Symfony\Component\Form\Extension\Core\Type\FileType;

  class ArtisteType extends AbstractType
 {
    public function buildForm(FormBuilderInterface $builder, array 
    $options)
  {
    $builder
        ->add('NomPrenom')
        ->add('adresse')
        ->add('image', FileType::class, array('required' => false))
        ->add('numero1')
        ->add('numero2')
        ->add('username')
        ->add('password',PasswordType::class)
    ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class' => Artiste::class,
    ]);
}
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥50 C++实现删除N个数据列表共有的元素
    • ¥15 Visual Studio问题
    • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
    • ¥20 求一个html代码,有偿
    • ¥100 关于使用MATLAB中copularnd函数的问题
    • ¥20 在虚拟机的pycharm上
    • ¥15 jupyterthemes 设置完毕后没有效果
    • ¥15 matlab图像高斯低通滤波
    • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
    • ¥15 钢筋实图交点识别,机器视觉代码