不允许序列化 \'SymfonyComponentHttpFoundationFileUploadedFile\'

本文介绍了不允许序列化 'SymfonyComponentHttpFoundationFileUploadedFile'的处理方法,对大家解决问题具有一定的参考价值

问题描述

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

用户实体:

isActive = true;$this->salt = md5(uniqid(null, true));}/*** 获取身份证** @return 整数*/公共函数 getId(){返回 $this->id;}/*** 设置姓氏** @param string $lastName* @return 用户*/公共函数 setLastName($lastName){$this->lastName = $lastName;返回 $this;}/*** 获取姓氏** @return 字符串*/公共函数 getLastName(){返回 $this->lastName;}/*** 设置名字** @param 字符串 $firstName* @return 用户*/公共函数 setFirstName($firstName){$this->firstName = $firstName;返回 $this;}/*** 获取名字** @return 字符串*/公共函数 getFirstName(){返回 $this->firstName;}/*** 设置工作** @param 字符串 $job* @return 用户*/公共函数 setJob($job){$this->job = $job;返回 $this;}/*** 找工作** @return 字符串*/公共函数 getJob(){返回 $this->job;}/*** 设置邮箱** @param string $email* @return 用户*/公共函数 setEmail($email){$this->email = $email;返回 $this;}/*** 获取电子邮件** @return 字符串*/公共函数 getEmail(){返回 $this->email;}/*** 设置密码** @param string $password* @return 用户*/公共函数 setPassword($password){$this->password = $password;返回 $this;}/*** 获取密码** @return 字符串*/公共函数 getPassword(){返回 $this->password;}/*** 放盐** @param 字符串 $salt* @return 用户*/公共函数 setSalt($salt){$this->salt = $salt;返回 $this;}/*** 拿盐** @return 字符串*/公共函数 getSalt(){返回 $this->salt;}/*** 设置角色** @param 数组 $role* @throws InvalidArgumentException* @return 用户*/公共函数 setRoles($role){if(array_diff($role, array("ROLE_SUPER_ADMIN", "ROLE_ADMIN", "ROLE_CUSTOMER"))) {throw new InvalidArgumentException("坏角色");}$this->roles = $role;返回 $this;}/*** 获取角色** @return 数组*/公共函数 getRoles(){返回 $this->roles;}/*** 设置 isActive** @param boolean $isActive* @return 用户*/公共函数 setIsActive($isActive){$this->isActive = $isActive;返回 $this;}/*** 获取 isActive** @return 布尔值*/公共函数 getIsActive(){返回 $this->isActive;}/*** @inheritDoc*/公共函数eraseCredentials(){}/*** 设置用户名** @param string $email** @return 字符串*/公共函数 setUsername($email){$this->email = $email;返回 $this;}/*** 获取用户名** @return 字符串*/公共函数 getUsername(){返回 $this->email;}公共函数 getAbsolutePath(){返回 null === $this->path ?null : $this->getUploadRootDir().'/'.$this->path;}公共函数 getWebPath(){返回 null === $this->path ?null : $this->getUploadDir().'/'.$this->path;}受保护的函数 getUploadRootDir(){返回 __DIR__.'/../../../../web/'.$this->getUploadDir();}受保护的函数 getUploadDir(){返回上传/img";}公共函数上传(){if (null === $this->file) {返回;} 别的 {$this->path = $this->firstName.'_'.$this->lastName.'_'.sha1(uniqid(mt_rand(), true)).'.'.$this->文件->guessExtension();}$this->file->move($this->getUploadRootDir(), $this->path);$this->file = null;}公共函数 getPath(){返回 $this->getWebPath();}}

用户类型:

$builder->add('firstName', 'text', array('必需' =>真的))->add('lastName', 'text', array('必需' =>真的))->add('email', 'email', array('必需' =>真的))->add('job', 'text', array('必需' =>错误的))->add('文件', '文件', 数组('标签' =>错误的,'必需' =>错误的,));

控制器:

 公共函数 updateMyAccountAction($id, Request $request){$entityManager = $this->get('doctrine')->getManager();$user = $this->get('doctrine')->getRepository('TestBackBundle:User')-> 查找($ id);如果(!$用户){throw $this->createNotFoundException('无法找到用户实体.');}$editForm = $this->createForm(new UserType(), $user);$editForm->handleRequest($request);如果 ($editForm->isValid()) {$用户->上传()$entityManager->persist($user);$entityManager->flush();$this->get('session')->getFlashBag()->add('success', '您的个人资料已更新');return $this->redirect($this->generateUrl('my_account', array('id' => $id)));} 别的 {$this->get('session')->getFlashBag()->add('error', 'Erreur');return $this->redirect($this->generateUrl('my_account', array('id' => $id)));}}

当我尝试测试图像断言是否可以更新 pdf 文件时,会发生此错误.文件没有更新,所以很好.但是我的闪存包和控制器中的重定向不起作用...如果我在控制器的 else 中写入 var_dump("test") 显示 "test"并且错误也是如此 Symfony 检测到表单无效.

这是发生错误时堆栈跟踪的一部分:

<块引用>

在/home/user/www/sf2/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.php在第 155 行

<代码>152.$this->角色,153. $this-> 属性154.)155.);}/**

<块引用>

在序列化(数组(对象(用户),真,数组(对象(角色)),数组()))在/home/kevin/www/sf2/vendor/symfony/symfony/src/Symfony/Component/Security/Core/Authentication/Token/AbstractToken.php在第 155 行

看了,感觉是roles属性序列化有问题,因为是数组(我们要声明这个属性为数组实现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 TestBackBundleEntity;

use DoctrineORMMapping as ORM;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentValidatorConstraints as Assert;
use SymfonyComponentHttpFoundationFileUploadedFile;
use SymfonyBridgeDoctrineValidatorConstraintsUniqueEntity;

/**
 * User
 *
 * @ORMTable(name="user")
 * @ORMEntity
 * @UniqueEntity(
 *     fields={"email"},
 *     message="This email already exists."
 *  )
 */
class User implements UserInterface
{
    /**
     * @var integer
     *
     * @ORMColumn(name="id", type="integer")
     * @ORMId
     * @ORMGeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORMColumn(name="lastName", type="string", length=255)
     * @AssertNotBlank()
     */
    private $lastName;

    /**
     * @var string
     *
     * @ORMColumn(name="firstName", type="string", length=255)
     * @AssertNotBlank()
     */
    private $firstName;

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

    /**
     * @var string
     *
     * @ORMColumn(name="email", type="string", length=255, unique=true)
     * @AssertEmail()
     */
    private $email;

    /**
     * @var string
     *
     * @ORMColumn(name="password", type="string", length=255)
     * @AssertNotBlank()
     */
    private $password;

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

    /**
     * @var array
     *
     * @ORMColumn(name="roles", type="array")
     * @AssertNotBlank()
     */
    private $roles;

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

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

    /**
     * @var string
     *
     * @AssertImage()
     */
    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

这篇关于不允许序列化 'SymfonyComponentHttpFoundationFileUploadedFile'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2

admin_action_{$_REQUEST[‘action’]}

do_action( "admin_action_{$_REQUEST[‘action’]}" )动作钩子::在发送“Action”请求变量时激发。Action Hook: Fires when an ‘action’ request variable is sent.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$_REQUEST['action']引用从GET或POST请求派生的操作。源码(Source)更新版本源码位置使用被使用2.6.0 wp-admin/admin.php:...

日期:2020-09-02 17:44:16 浏览:1163

admin_footer-{$GLOBALS[‘hook_suffix’]}

do_action( "admin_footer-{$GLOBALS[‘hook_suffix’]}", string $hook_suffix )操作挂钩:在默认页脚脚本之后打印脚本或数据。Action Hook: Print scripts or data after the default footer scripts.目录锚点:#说明#参数#源码说明(Description)钩子名的动态部分,$GLOBALS['hook_suffix']引用当前页的全局钩子后缀。参数(Parameters)参数类...

日期:2020-09-02 17:44:20 浏览:1065

customize_save_{$this->id_data[‘base’]}

do_action( "customize_save_{$this-&gt;id_data[‘base’]}", WP_Customize_Setting $this )动作钩子::在调用WP_Customize_Setting::save()方法时激发。Action Hook: Fires when the WP_Customize_Setting::save() method is called.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_data...

日期:2020-08-15 15:47:24 浏览:802

customize_value_{$this->id_data[‘base’]}

apply_filters( "customize_value_{$this-&gt;id_data[‘base’]}", mixed $default )过滤器::过滤未作为主题模式或选项处理的自定义设置值。Filter Hook: Filter a Customize setting value not handled as a theme_mod or option.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_date['base'],指的是设置...

日期:2020-08-15 15:47:24 浏览:892

get_comment_author_url

过滤钩子:过滤评论作者的URL。Filter Hook: Filters the comment author’s URL.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/comment-template.php:32610...

日期:2020-08-10 23:06:14 浏览:927

network_admin_edit_{$_GET[‘action’]}

do_action( "network_admin_edit_{$_GET[‘action’]}" )操作挂钩:启动请求的处理程序操作。Action Hook: Fires the requested handler action.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$u GET['action']引用请求的操作的名称。源码(Source)更新版本源码位置使用被使用3.1.0 wp-admin/network/edit.php:3600...

日期:2020-08-02 09:56:09 浏览:874

network_sites_updated_message_{$_GET[‘updated’]}

apply_filters( "network_sites_updated_message_{$_GET[‘updated’]}", string $msg )筛选器挂钩:在网络管理中筛选特定的非默认站点更新消息。Filter Hook: Filters a specific, non-default site-updated message in the Network admin.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分$_GET['updated']引用了非默认的...

日期:2020-08-02 09:56:03 浏览:858

pre_wp_is_site_initialized

过滤器::过滤在访问数据库之前是否初始化站点的检查。Filter Hook: Filters the check for whether a site is initialized before the database is accessed.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/ms-site.php:93910...

日期:2020-07-29 10:15:38 浏览:828

WordPress 的SEO 教学:如何在网站中加入关键字(Meta Keywords)与Meta 描述(Meta Description)?

你想在WordPress 中添加关键字和meta 描述吗?关键字和meta 描述使你能够提高网站的SEO。在本文中,我们将向你展示如何在WordPress 中正确添加关键字和meta 描述。为什么要在WordPress 中添加关键字和Meta 描述?关键字和说明让搜寻引擎更了解您的帖子和页面的内容。关键词是人们寻找您发布的内容时,可能会搜索的重要词语或片语。而Meta Description则是对你的页面和文章的简要描述。如果你想要了解更多关于中继标签的资讯,可以参考Google的说明。Meta 关键字和描...

日期:2020-10-03 21:18:25 浏览:1708

谷歌的SEO是什么

SEO (Search Engine Optimization)中文是搜寻引擎最佳化,意思近于「关键字自然排序」、「网站排名优化」。简言之,SEO是以搜索引擎(如Google、Bing)为曝光媒体的行销手法。例如搜寻「wordpress教学」,会看到本站的「WordPress教学:12个课程…」排行Google第一:关键字:wordpress教学、wordpress课程…若搜寻「网站架设」,则会看到另一个网页排名第1:关键字:网站架设、架站…以上两个网页,每月从搜寻引擎导入自然流量,达2万4千:每月「有机搜...

日期:2020-10-30 17:23:57 浏览:1303