不允许序列化"Symfony \ Component \ HttpFoundation \ File \ UploadedFile"(仅当我修改图像时) [英] Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed (only when i modify the image)

查看:62
本文介绍了不允许序列化"Symfony \ Component \ HttpFoundation \ File \ UploadedFile"(仅当我修改图像时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我正在尝试做一张表格来修改个人资料的图像.一切正常,但是当我放大尺寸的图像(除数据库中的图像以外,我的图像超出了其他所有尺寸)时,出现此错误:

Hello guys i am trying to do a form to modify the image of a profile. All work well but when i put an image with a big size (more than i except in the data base) i have this error :

不允许对"Symfony \ Component \ HttpFoundation \ File \ UploadedFile"进行序列化

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

我不知道为什么约束不起作用...(在我创建配置文件时有效,但在我修改配置文件时无效)

I don't know why the constraints is not working ... (it works when i create a profile but not when i modify it) thx for all that will try to answer

我将代码放在这里:(控制器)

I put my code right there : (controller)

    $loggedAs = $this->getUser();
    $avatar_profile = $loggedAs->getAvatarPath();
    $em = $this->getDoctrine()->getManager();

$form = $this->createForm(ProfileModificationType::class, $loggedAs);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        /**
         * @var UploadedFile $file
         */
        $file = $form->get('avatarPath')->getData();
        if ($file != NULL) {
            $fileName = md5(uniqid()) . '.' . $file->guessExtension();

            $file->move(
                $this->getParameter('image_directory'), $fileName
            );
            $loggedAs->setAvatarPath($fileName);
        } else {
            $loggedAs->setAvatarPath($avatar_profile);
        }
        $loggedAs->setSalt(md5(uniqid()));

        $loggedAs->setPassword($encoder->encodePassword($loggedAs, $loggedAs->getPassword()));
        $em->flush();

        $this->get('session')->getFlashBag()->add('success', "Votre compte a été modifié");

表格:

->add('avatarPath', FileType::class, array(
            'data_class' => null,
            'required' => false,
            'label' => 'Avatar',
            'constraints' => array(
                new Assert\Image(array(
                    'maxHeight' => 600,
                    'maxWidth' => 600,
                    'maxSize' => 1000000,
                    'maxHeightMessage' => 'Longeur maximale de 600Px',
                    'maxWidthMessage' => 'Largeur maximale de 600Px',
                    'maxSizeMessage' => 'Taille maximale de 1Mo',
                ))),
            'invalid_message' => 'Cette valeur est invalide',
        ));

和我的实体资料(约束)中:

and in my entity profile (constraint):

public static function loadValidatorMetadata(ClassMetadata $metadata)
{
    $metadata->addPropertyConstraint('avatarPath', new Assert\Image(array(
        'maxHeight' => 600,
        'maxWidth' => 600,
        'maxSize' => 1000000,
        'maxHeightMessage' => 'Longeur maximale de 600Px',
        'maxWidthMessage' => 'Largeur maximale de 600Px',
        'maxSizeMessage' => 'Taille maximale de 1Mo',
    )));
}

和我的实体

/**
 * @var string
 *
 * @ORM\Column(name="avatar_path", type="string", length=255, nullable=false)
 */
private $avatarPath;

当我修改实体时,我尝试序列化该实体,但是我遇到了相同的错误……也许我做错了,我把为序列化而更改的代码放给您.

I tried to serialize the entity when i modify it but i have the same error ... maybe i do it wrong, i put you the code that i change for serialize it.

/**
* Profile
*
* @UniqueEntity(fields="email", message="Cette adresse mail est déjà 
utilisée")
* @ORM\Table(name="profile", uniqueConstraints= 
{@ORM\UniqueConstraint(name="UNIQ_8157AA0FE7927C74", columns= 
{"email"})})
* 
@ORM\Entity(repositoryClass="AppBundle\Repository\ProfileRepository")
*/
class Profile implements UserInterface, \Serializable
{
const ROLE_USER = 'ROLE_USER';
const ROLE_ADMIN = 'ROLE_ADMIN';

/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="salt", type="string", length=40)
 */
private $salt;

/**
 * @var string
 *
 * @ORM\Column(name="stripe_customer_id", type="string", length=100, nullable=true)
 */
private $stripeCustomerId;

/**
 * @var string
 *
 * @ORM\Column(name="first_name", type="string", length=25, nullable=false)
 */
private $firstName;

/**
 * @var string
 *
 * @ORM\Column(name="second_name", type="string", length=25, nullable=false)
 */
private $secondName;

/**
 * @var string
 *
 * @ORM\Column(name="society", type="string", length=30, nullable=false)
 */
private $society;

/**
 * @var string
 *
 * @ORM\Column(name="t_card", type="string", length=30, nullable=false)
 */
private $tCard;

/**
 * @var boolean
 *
 * @ORM\Column(name="t_card_propriety", type="boolean", nullable=true)
 */
private $tCardPropriety;

/**
 * @var string
 *
 * @ORM\Column(name="siret", type="string", length=25, nullable=false)
 */
private $siret;

/**
 * @var integer
 *
 * @ORM\Column(name="collaborators", type="integer", nullable=false)
 */
private $collaborators;

/**
 * @var string
 *
 * @ORM\Column(name="address", type="string", length=25, nullable=false)
 */
private $address;

/**
 * @var integer
 *
 * @ORM\Column(name="postal_code", type="integer", nullable=false)
 */
private $postalCode;

/**
 * @var string
 *
 * @ORM\Column(name="city", type="string", length=20, nullable=false)
 */
private $city;

/**
 * @var boolean
 *
 * @ORM\Column(name="software_solution", type="boolean", nullable=true)
 */
private $softwareSolution;

/**
 * @var string
 *
 * @ORM\Column(name="software_solution_name", type="string", length=255, nullable=true)
 */
private $softwareSolutionName;

/**
 * @var string
 *
 * @ORM\Column(name="avatar_path", type="string", length=255, nullable=false)
 */
private $avatarPath;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="last_connexion", type="datetime", nullable=false)
 */
private $lastConnexion;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="created_account", type="datetime", nullable=false)
 */
private $createdAccount;

/**
 * @var string
 *
 * @ORM\Column(name="email", type="string", length=60, nullable=false, unique=true)
 */
private $email;

/**
 * @var string
 *
 * @ORM\Column(name="password", type="text", nullable=false)
 * @Assert\Regex(
 *     pattern="/(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#\$%\^&\*])(?=.*[0-9]).{7,}/",
 *     message="Le mot de passe doit être constitué de 8 caratères, une majuscule, une minuscule, un caractère special et un chiffre au minimum",
 *     groups={"Default", "Patch"}
 * )
 */
private $password;

/**
 * @var array
 *
 * @ORM\Column(name="roles", type="simple_array", length=255, nullable=false)
 */
private $roles;

/**
 * @var integer
 *
 * @ORM\Column(name="mandates", type="integer", nullable=false)
 */
private $mandates;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="last_mandate", type="datetime", nullable=true)
 */
private $lastMandate;

/**
 * @var \DateTime
 *
 * @ORM\Column(name="second_last_mandate", type="datetime", nullable=true)
 */
private $secondLastMandate;

/**
 * @var \AppBundle\Entity\ProfileStatus
 *
 * @ORM\ManyToOne(targetEntity="ProfileStatus")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="status", referencedColumnName="id")
 * })
 */
private $status;

/**
 * @var integer
 *
 * @ORM\Column(name="enabled", type="integer", nullable=false)
 */
private $enabled;

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

/**
 * @return int
 */
public function getId()
{
    return $this->id;
}

/**
 * @param int $id
 */
public function setId($id)
{
    $this->id = $id;
}

/**
 * @return string
 */
public function getFirstName()
{
    return $this->firstName;
}

/**
 * @param string $firstName
 */
public function setFirstName($firstName)
{
    $this->firstName = $firstName;
}

/**
 * @return string
 */
public function getSecondName()
{
    return $this->secondName;
}

/**
 * @param string $secondName
 */
public function setSecondName($secondName)
{
    $this->secondName = $secondName;
}

/**
 * @return string
 */
public function getSociety()
{
    return $this->society;
}

/**
 * @param string $society
 */
public function setSociety($society)
{
    $this->society = $society;
}

/**
 * @return string
 */
public function getTCard()
{
    return $this->tCard;
}

/**
 * @param string $tCard
 */
public function setTCard($tCard)
{
    $this->tCard = $tCard;
}

/**
 * @return bool
 */
public function isTCardPropriety()
{
    return $this->tCardPropriety;
}

/**
 * @param bool $tCardPropriety
 */
public function setTCardPropriety($tCardPropriety)
{
    $this->tCardPropriety = $tCardPropriety;
}

/**
 * @return string
 */
public function getSiret()
{
    return $this->siret;
}

/**
 * @param string $siret
 */
public function setSiret($siret)
{
    $this->siret = $siret;
}

/**
 * @return int
 */
public function getCollaborators()
{
    return $this->collaborators;
}

/**
 * @param int $collaborators
 */
public function setCollaborators($collaborators)
{
    $this->collaborators = $collaborators;
}

/**
 * @return string
 */
public function getAddress()
{
    return $this->address;
}

/**
 * @param string $address
 */
public function setAddress($address)
{
    $this->address = $address;
}

/**
 * @return int
 */
public function getPostalCode()
{
    return $this->postalCode;
}

/**
 * @param int $postalCode
 */
public function setPostalCode($postalCode)
{
    $this->postalCode = $postalCode;
}

/**
 * @return string
 */
public function getCity()
{
    return $this->city;
}

/**
 * @param string $city
 */
public function setCity($city)
{
    $this->city = $city;
}

/**
 * @return bool
 */
public function isSoftwareSolution()
{
    return $this->softwareSolution;
}

/**
 * @param bool $softwareSolution
 */
public function setSoftwareSolution($softwareSolution)
{
    $this->softwareSolution = $softwareSolution;
}

/**
 * @return string
 */
public function getSoftwareSolutionName()
{
    return $this->softwareSolutionName;
}

/**
 * @param string $softwareSolutionName
 */
public function setSoftwareSolutionName($softwareSolutionName)
{
    $this->softwareSolutionName = $softwareSolutionName;
}

/**
 * @return string
 */
public function getAvatarPath()
{
    return $this->avatarPath;
}

/**
 * @param string $avatarPath
 */
public function setAvatarPath($avatarPath)
{
    $this->avatarPath = $avatarPath;
}

/**
 * @return \DateTime
 */
public function getLastConnexion()
{
    return $this->lastConnexion;
}

/**
 * @param \DateTime $lastConnexion
 */
public function setLastConnexion($lastConnexion)
{
    $this->lastConnexion = $lastConnexion;
}

/**
 * @return \DateTime
 */
public function getCreatedAccount()
{
    return $this->createdAccount;
}

/**
 * @param \DateTime $createdAccount
 */
public function setCreatedAccount($createdAccount)
{
    $this->createdAccount = $createdAccount;
}

/**
 * @return string
 */
public function getEmail()
{
    return $this->email;
}

/**
 * @param string $email
 */
public function setEmail($email)
{
    $this->email = $email;
}

/**
 * @return string
 */
public function getPassword()
{
    return $this->password;
}

/**
 * @param string $password
 */
public function setPassword($password)
{
    $this->password = $password;
}

/**
 * @return array
 */
public function getRoles()
{
    return $this->roles;
}

/**
 * @param array $roles
 */
public function setRoles($roles)
{
    $this->roles = $roles;
}

/**
 * @return int
 */
public function getMandates()
{
    return $this->mandates;
}

/**
 * @param int $mandates
 */
public function setMandates($mandates)
{
    $this->mandates = $mandates;
}

/**
 * @return \DateTime
 */
public function getLastMandate()
{
    return $this->lastMandate;
}

/**
 * @param \DateTime $lastMandate
 */
public function setLastMandate($lastMandate)
{
    $this->lastMandate = $lastMandate;
}

/**
 * @return \DateTime
 */
public function getSecondLastMandate()
{
    return $this->secondLastMandate;
}

/**
 * @param \DateTime $secondLastMandate
 */
public function setSecondLastMandate($secondLastMandate)
{
    $this->secondLastMandate = $secondLastMandate;
}

/**
 * @return string
 */
public function getStatus()
{
    return $this->status;
}

/**
 * @param string $status
 */
public function setStatus($status)
{
    $this->status = $status;
}

/**
 * @return int
 */
public function getEnabled()
{
    return $this->enabled;
}

/**
 * @param int $enabled
 */
public function setEnabled($enabled)
{
    $this->enabled = $enabled;
}

/**
 * @return int
 */
public function getPhone()
{
    return $this->phone;
}

/**
 * @param int $phone
 */
public function setPhone($phone)
{
    $this->phone = $phone;
}

/**
 * Removes sensitive data from the user.
 *
 * This is important if, at any given point, sensitive information like
 * the plain-text password is stored on this object.
 */
public function eraseCredentials()
{
    // TODO: Implement eraseCredentials() method.
}

/**
 * Returns the username used to authenticate the user.
 *
 * @return string The username
 */
public function getUsername()
{
    return $this->getEmail();
}

public static function loadValidatorMetadata(ClassMetadata $metadata)
{
    $metadata->addPropertyConstraint('email', new Assert\NotBlank(array(
        'message' => 'Cette valeur ne doit pas être vide !',
    )));
    $metadata->addPropertyConstraint('password', new Assert\NotBlank(array(
        'message' => 'Cette valeur ne doit pas être vide !',
    )));
    $metadata->addPropertyConstraint('firstName', new Assert\NotBlank(array(
        'message' => 'Cette valeur ne doit pas être vide !',
    )));
    $metadata->addPropertyConstraint('secondName', new Assert\NotBlank(array(
        'message' => 'Cette valeur ne doit pas être vide !',
    )));
    $metadata->addPropertyConstraint('society', new Assert\NotBlank(array(
        'message' => 'Cette valeur ne doit pas être vide !',
    )));
    $metadata->addPropertyConstraint('avatarPath', new Assert\Image(array(
        'maxHeight' => 600,
        'maxWidth' => 600,
        'maxSize' => 1000000,
        'maxHeightMessage' => 'Longeur maximale de 600Px',
        'maxWidthMessage' => 'Largeur maximale de 600Px',
        'maxSizeMessage' => 'Taille maximale de 1Mo',
    )));
}

/**
 * @return string
 */
public function getSalt()
{
    return $this->salt;
}

/**
 * @param string $salt
 */
public function setSalt($salt)
{
    $this->salt = $salt;
}

/**
 * @return string
 */
public function getStripeCustomerId()
{
    return $this->stripeCustomerId;
}

/**
 * @param string $stripeCustomerId
 */
public function setStripeCustomerId($stripeCustomerId)
{
    $this->stripeCustomerId = $stripeCustomerId;
}

/**
 * String representation of object
 * @link http://php.net/manual/en/serializable.serialize.php
 * @return string the string representation of the object or null
 * @since 5.1.0
 */
public function serialize()
{
    return serialize(array(
        $this->id,
        $this->firstName,
        $this->secondName,
        $this->society,
        $this->tCard,
        $this->tCardPropriety,
        $this->siret,
        $this->collaborators,
        $this->address,
        $this->postalCode,
        $this->city,
        //$this->softwareSolution,
        //$this->softwareSolutionName,
        $this->avatarPath,
        //$this->lastConnexion,
        //$this->createdAccount,
        $this->email,
        $this->password,
        //$this->roles,
        //$this->mandates,
        //$this->lastMandate,
        //$this->secondLastMandate,
        //$this->enabled,
        //$this->phone,
        //$this->status,
        //$this->salt,
        //$this->stripeCustomerId,
    ));
}

/**
 * Constructs the object
 * @link http://php.net/manual/en/serializable.unserialize.php
 * @param string $serialized <p>
 * The string representation of the object.
 * </p>
 * @return void
 * @since 5.1.0
 */
public function unserialize($serialized)
{
    list (
        $this->id,
        $this->firstName,
        $this->secondName,
        $this->society,
        $this->tCard,
        $this->siret,
        $this->tCardPropriety,
        $this->collaborators,
        $this->address,
        $this->postalCode,
        $this->city,
        //$this->softwareSolution,
        //$this->softwareSolutionName,
        $this->avatarPath,
        //$this->lastConnexion,
        //$this->createdAccount,
        $this->email,
        $this->password,
        //$this->roles,
        //$this->mandates,
        //$this->lastMandate,
        //$this->secondLastMandate,
        //$this->enabled,
        //$this->phone,
        //$this->status,
        //$this->salt,
        //$this->stripeCustomerId,
        ) = unserialize($serialized, array('allowed_classes' => false));
}
}

推荐答案

问题是"avatar_path"是一个字符串,但是您的表单正在等待文件,因此我建议添加选项"mapping => false":

the problem is that "avatar_path" is a string, but your form is waiting for a file, I propose to add the option "mapping => false" :

 ->add('avatarPath', FileType::class, array(
        'data_class' => null,
        'required' => false,
        'label' => 'Avatar',
        'constraints' => array(
            new Assert\Image(array(
                'maxHeight' => 600,
                'maxWidth' => 600,
                'maxSize' => 1000000,
                'maxHeightMessage' => 'Longeur maximale de 600Px',
                'maxWidthMessage' => 'Largeur maximale de 600Px',
                'maxSizeMessage' => 'Taille maximale de 1Mo',
            ))),
        'invalid_message' => 'Cette valeur est invalide',
        'mapped'=>false
    ));

或添加另一个用于formType的标志:

Or to add another flag to use in the formType :

  /**
   * @var string
   *
   * @ORM\Column(name="avatar_path", type="string", length=255,nullable=false)
   */
   private $avatarPath;


  /**
   * @Assert\File(
   *     maxSize = "512k",
   *     maxSizeMessage = "...",
   *     mimeTypes={ "image/png",
   *          "image/jpeg",
   *          "image/jpg",
   *          "image/x-icon",
   *          "image/pdf"},
   *     groups={""}
   * )
   */
   private $avatar;

这篇关于不允许序列化"Symfony \ Component \ HttpFoundation \ File \ UploadedFile"(仅当我修改图像时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆