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

时间:2019-05-22 15:43:55

标签: php serialization image-uploading symfony4

我已将头像图像添加到我的User类。当我要呈现编辑表单时,出现此错误

不允许对“ Symfony \ Component \ HttpFoundation \ File \ File”进行序列化

我试图通过根据Symfony官方文档在User类中实现\ Serializable解决此问题。但是didint工作。

这是我的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));
}

} 这是我的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(),
    ]);
}

这是我的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 个答案:

没有答案