“Symfony \ Component \HttpFoundation\File\UploadedFile”的序列化是不允许的 [英] Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed

查看:259
本文介绍了“Symfony \ Component \HttpFoundation\File\UploadedFile”的序列化是不允许的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试上传与图像断言不匹配的错误文件时,会发生此错误。



用户实体:

 < php 

命名空间Test \BackBundle\Entity;

使用Doctrine \ORM\Mapping作为ORM;
使用Symfony \ Component \Security\Core\User\UserInterface;
使用Symfony \ Component \Vididator\Constraints as Assert;
使用Symfony \ Component \HttpFoundation\File\UploadedFile;
使用Symfony \ Bridge \Doctrine\Validator\Constraints\UniqueEntity;
$ b / **
* User
*
* @ ORM\Table(name =user)
* @ ORM\Entity
* @UniqueEntity(
* fields = {email},
* message =这封电子邮件已经存在。
*)
* /
类User实现UserInterface
{
/ **
* @var整数
*
* @ ORM \Column(name =id,type =integer )
* @ ORM\Id
* @ ORM\GeneratedValue(strategy =AUTO)
* /
private $ id;
$ b / **
* @var字符串
*
* @ ORM\Column(name =lastName,type =string,length = 255 )
* @ Assert\NotBlank()
* /
private $ lastName;
$ b / **
* @var字符串
*
* @ ORM\Column(name =firstName,type =string,length = 255 )
* @ Assert\NotBlank()
* /
private $ firstName;
$ b / **
* @var字符串
*
* @ ORM \Column(name =job,type =string,length = 255 ,nullable = true)
* /
private $ job;
$ b / **
* @var字符串
*
* @ ORM \Column(name =email,type =string,length = 255 ,unique = true)
* @ Assert\Email()
* /
private $ email;
$ b / **
* @var字符串
*
* @ ORM \Column(name =password,type =string,length = 255 )
* @ Assert\NotBlank()
* /
private $ password;
$ b $ **
* @var字符串
*
* @ ORM\Column(name =salt,type =string,length = 255 )
* /
私人$盐;
$ b $ **
* @var数组
*
* @ ORM\Column(name =roles,type =array)
* @ Assert \NotBlank()
* /
private $ roles;
$ b $ **
* @var boolean
*
* @ ORM\Column(name =isActive,type =boolean)
* /
private $ isActive;
$ b / **
* @var字符串
*
* @ ORM \Column(name =avatar,type =string,length = 255 ,nullable = true)
* /
private $ path;
$ b / **
* @var字符串
*
* @ Assert\Image()
* /
public $ file;

public function __construct()
{
$ this-> isActive = true;
$ this-> salt = md5(uniqid(null,true));

$ b / **
*获取id
*
* @return整数
* /
public function getId )
{
return $ this-> id;

$ b $ **
*设置姓氏
*
* @param字符串$姓氏
* @return用户
* /
public function setLastName($ lastName)
{
$ this-> lastName = $ lastName;

返回$ this;

$ b / **
*获取姓氏
*
* @return字符串
* /
public function getLastName )
{
return $ this-> lastName;

$ b $ **
设置名字
*
* @param字符串$名字
* @return用户
* /
public function setFirstName($ firstName)
{
$ this-> firstName = $ firstName;

返回$ this;

$ b $ **
获取名字
*
* @return string
* /
public function getFirstName )
{
return $ this-> firstName;

$ b / **
*设置工作
*
* @param字符串$工作
* @返回用户
* /
public function setJob($ job)
{
$ this-> job = $ job;

返回$ this;

$ b / **
*获得工作
*
* @return string
* /
public function getJob )
{
return $ this-> job;

$ b $ **
设置电子邮件
*
* @param字符串$电子邮件
* @return用户
* /
public function setEmail($ email)
{
$ this-> email = $ email;

返回$ this;

$ b / **
*获取电子邮件
*
* @return string
* /
public function getEmail( )
{
return $ this-> email;

$ b $ **
*设置密码
*
* @param字符串$密码
* @return用户
* /
public function setPassword($ password)
{
$ this-> password = $ password;

返回$ this;

$ b / **
*获取密码
*
* @return字符串
* /
public function getPassword )
{
return $ this-> password;

$ b / **
*设置salt
*
* @param string $ salt
* @return User
* /
public function setSalt($ salt)
{
$ this-> salt = $ salt;

返回$ this;

$ b $ ** b $ b *得到salt
*
* @return string
* /
public function getSalt )
{
return $ this-> salt;

$ b $ ** b $ b *设置角色
*
* @param array $ role
* @throws \InvalidArgumentException $ b ($ role),array(ROLE_SUPER_ADMIN,ROLE_ADMIN,$ b $ @ ROLE_CUSTOMER))){
throw new \InvalidArgumentException(Bad role);
}
$ this-> roles = $ role;

返回$ this;

$ b / **
*获取角色
*
* @return数组
* /
public function getRoles )
{
return $ this->角色;

$ b $ **
* set isActive
*
* @param boolean $ isActive
* @return User
* /
public function setIsActive($ isActive)
{
$ this-> isActive = $ isActive;

返回$ this;

$ b / **
*获取isActive
*
* @return boolean
* /
public function getIsActive )
{
return $ this-> isActive;

$ b / **
* @inheritDoc
* /
public function eraseCredentials()
{
}
$ b $ **
*设置用户名
*
* @param字符串$电子邮件
*
* @return字符串
* /
public function setUsername($ email)
{
$ this-> email = $ email;

返回$ this;

$ b / **
*获取用户名
*
* @return字符串
* /
public function getUsername )
{
return $ this-> email;


public function getAbsolutePath()
{
return null === $ this-> path? null:$ this-> getUploadRootDir()。'/'。$ this-> path;


public function getWebPath()
{
return null === $ this-> path? null:$ this-> getUploadDir()。'/'。$ this-> path;


protected function getUploadRootDir()
{
return __DIR __。'/ .. / .. / .. / .. / web /'.$ this - > getUploadDir();


protected function getUploadDir()
{
return'uploads / img';


public function upload()
{
if(null === $ this-> file){
return;
} else {
$ this-> path = $ this-> firstName .'_'。$ this-> lastName。'_'。sha1(uniqid(mt_rand(),true) )这 - $> '';文件 - > guessExtension();
}

$ this-> file-> move($ this-> getUploadRootDir(),$ this-> path);

$ this-> file = null;


public function getPath()
{
return $ this-> getWebPath();

$ b $ / code $ / pre
$ b $用户类型/

  $ builder 
- > add('firstName','text',array(
'required'=> true
))
- > add('lastName','text',array(
'required'=> true
))
- > add('email ','email',array(
'required'=> true
))
- > add('job','text',array(
'required '=> false
))
- > add('file','file',array(
'label'=> false,
'required'= > false,
))
;

控制器:

  public function updateMyAccountAction($ id,Request $ request)
{
$ entityManager = $ this-> get('doctrine') - > getManager();
$ b $ user $ $ this-> get('doctrine')
- > getRepository('TestBackBundle:User')
- > find($ id);
$ b $ if(!$ user){
throw $ this-> createNotFoundException('Unable to find User entity。');

$ b $ editForm = $ this-> createForm(new UserType(),$ user);

$ editForm-> handleRequest($ request); ($ editForm-> isValid()){

$ user-> upload();

if

$ entityManager-> persist($ user);
$ entityManager-> flush();
$ this-> get('session') - > getFlashBag() - > add('success','Your profile has been updated');

return $ this-> redirect($ this-> generateUrl('my_account',array('id'=> $ id)));
$ else this $> get('session') - > getFlashBag() - > add('error','Erreur');

return $ this-> redirect($ this-> generateUrl('my_account',array('id'=> $ id)));




$ b当我尝试测试图像断言是否工作更新例如一个PDF文件,这个错误发生。该文件没有更新,所以它是好的。但我的控制器中的闪存包和重定向不起作用...如果我在我的控制器中写入 var_dump(test) else 显示test,错误也是如此,Symfony检测到表单无效。

这是Stack Trace的一部分错误发生:

lockquote
$ b $ home / user / www / sf2 / vendor / symfony / symfony / src / Symfony / Component /Security/Core/Authentication/Token/AbstractToken.php
at line 155




  152。 $ this->角色,
153. $ this->属性
154.)
155.);





at serialize (array(object(User),true,array(object(Role)),array()))

/ home / kevin / www / sf2 / vendor / symfony / symfony / src / Symfony /Component/Security/Core/Authentication/Token/AbstractToken.php
at line 155


阅读它,我觉得因为它是一个数组(我们必须声明这个属性为一个实现 UserInterface 的数组)。

那么为什么会出现这个错误呢?

解决方案

我找到了解决方案:我必须实现 Serializable 像这样:官方文档


This error occurs when I try to upload a bad file which does not match with the image assert. Only image are accepted.

user entity :

<?php

namespace Test\BackBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity
 * @UniqueEntity(
 *     fields={"email"},
 *     message="This email already exists."
 *  )
 */
class User implements UserInterface
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="lastName", type="string", length=255)
     * @Assert\NotBlank()
     */
    private $lastName;

    /**
     * @var string
     *
     * @ORM\Column(name="firstName", type="string", length=255)
     * @Assert\NotBlank()
     */
    private $firstName;

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

    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=255, unique=true)
     * @Assert\Email()
     */
    private $email;

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

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

    /**
     * @var array
     *
     * @ORM\Column(name="roles", type="array")
     * @Assert\NotBlank()
     */
    private $roles;

    /**
     * @var boolean
     *
     * @ORM\Column(name="isActive", type="boolean")
     */
    private $isActive;

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

    /**
     * @var string
     *
     * @Assert\Image()
     */
    public $file;

    public function __construct()
    {
        $this->isActive = true;
        $this->salt = md5(uniqid(null, true));
    }

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

    /**
     * Set lastName
     *
     * @param string $lastName
     * @return User
     */
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * Get lastName
     *
     * @return string 
     */
    public function getLastName()
    {
        return $this->lastName;
    }

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

        return $this;
    }

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

    /**
     * Set job
     *
     * @param string $job
     * @return User
     */
    public function setJob($job)
    {
        $this->job = $job;

        return $this;
    }

    /**
     * Get job
     *
     * @return string 
     */
    public function getJob()
    {
        return $this->job;
    }

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

        return $this;
    }

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

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

        return $this;
    }

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

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

        return $this;
    }

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

    /**
     * Set role
     *
     * @param array $role
     * @throws \InvalidArgumentException
     * @return User
     */
    public function setRoles($role)
    {
        if(array_diff($role, array("ROLE_SUPER_ADMIN", "ROLE_ADMIN", "ROLE_CUSTOMER"))) {
            throw new \InvalidArgumentException("Bad role");
        }
        $this->roles = $role;

        return $this;
    }

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

    /**
     * Set isActive
     *
     * @param boolean $isActive
     * @return User
     */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;

        return $this;
    }

    /**
     * Get isActive
     *
     * @return boolean 
     */
    public function getIsActive()
    {
        return $this->isActive;
    }

    /**
     * @inheritDoc
     */
    public function eraseCredentials()
    {
    }

    /**
     * Set username
     *
     * @param string $email
     *
     * @return string
     */
    public function setUsername($email)
    {
        $this->email = $email;

        return $this;
    }

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

    public function getAbsolutePath()
    {
        return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->path;
    }

    public function getWebPath()
    {
        return null === $this->path ? null : $this->getUploadDir().'/'.$this->path;
    }

    protected function getUploadRootDir()
    {
        return __DIR__.'/../../../../web/'.$this->getUploadDir();
    }

    protected function getUploadDir()
    {
        return 'uploads/img';
    }

    public function upload()
    {
        if (null === $this->file) {
            return;
        } else {
            $this->path = $this->firstName.'_'.$this->lastName.'_'.sha1(uniqid(mt_rand(), true)).'.'.$this->file->guessExtension();
        }

        $this->file->move($this->getUploadRootDir(), $this->path);

        $this->file = null;
    }

    public function getPath()
    {
        return $this->getWebPath();
    }
}

userType:

$builder
    ->add('firstName', 'text', array(
                    'required' => true
                ))
     ->add('lastName', 'text', array(
                    'required' => true
                ))
     ->add('email', 'email', array(
                    'required' => true
                ))
     ->add('job', 'text', array(
                    'required' => false
                ))
     ->add('file', 'file', array(
                    'label' => false,
                    'required' => false,
                ))
            ;

controller :

    public function updateMyAccountAction($id, Request $request)
    {
        $entityManager = $this->get('doctrine')->getManager();

        $user = $this->get('doctrine')
            ->getRepository('TestBackBundle:User')
            ->find($id);

        if (!$user) {
            throw $this->createNotFoundException('Unable to find User entity.');
        }

        $editForm = $this->createForm(new UserType(), $user);

        $editForm->handleRequest($request);

        if ($editForm->isValid()) {

            $user->upload();

            $entityManager->persist($user);
            $entityManager->flush();
            $this->get('session')->getFlashBag()->add('success', 'Your profile has been updated');

            return $this->redirect($this->generateUrl('my_account', array('id' => $id)));
        } else {
            $this->get('session')->getFlashBag()->add('error', 'Erreur');

            return $this->redirect($this->generateUrl('my_account', array('id' => $id)));
        }
    }

When I try to test if the image assert works updating for example a pdf file, this error occurs. The file is not updated so it is good. But my flash bag and redirection in my controller don't work... if I write var_dump("test") in the else in my controller "test" is displayed and the error too so Symfony detects that the form is not valid.

This is a part of the Stack Trace when error occurs :

in /home/user/www/sf2/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.php at line 155

152.                $this->roles,
153.                $this->attributes
154.            )
155.        );
    }
    /**

at serialize (array(object(User), true, array(object(Role)), array())) in /home/kevin/www/sf2/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.php at line 155

Reading it, I feel that there is a problem with the roles attribute to serialize it because it is an array (we have to declare this attribute as an array implementing UserInterface)

So why this error occurs ?

解决方案

I have found the solution : I had to implement Serializable interface like this : official doc

这篇关于“Symfony \ Component \HttpFoundation\File\UploadedFile”的序列化是不允许的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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