【问题标题】:setFile() must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile, string givensetFile() 必须是 Symfony\Component\HttpFoundation\File\UploadedFile 的实例,给定字符串
【发布时间】:2015-07-31 16:51:45
【问题描述】:

我正在处理一个 silex 项目的学说和表格。我已经创建了一个文件表单域,但是当我选择一个文件并提交表单时,会出现下一个错误。

传递给 models\Page::setFile() 的参数 1 必须是 Symfony\Component\HttpFoundation\File\UploadedFile 的实例,给定字符串,在 /Applications/MAMP/htdocs/admin/vendor/symfony/property- 中调用在第 410 行访问/PropertyAccessor.php 并定义

$request->files 也是空的,当我调用$form->handleRequest($request) 函数时会出现错误。

formbuilder Pagetype.php

<?php
namespace forms\type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityRepository;

class PageType extends AbstractType
{

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $this->id = $options['data']->id;
    if($this->id == null){$this->id = 0;}
    $builder
        ->add('title', 'text', array('attr' => array('class'=>'form-control')))
        ->add('slug', 'text', array('required' => false,
                'attr' => array('class'=>'form-control')
            ))
        ->add('intro', 'textarea')
        ->add('text', 'textarea')
        ->add('file', 'file', array("required" => false,
                                "file_path" => UPLOAD_DIR,
                                "file_name" => "path",))

        ->add('tags', 'collection', array(
                'type' => new TagType(), 
                'options' => array('label' => false, 'attr'=>array('class'=>'form_collection_item clearfix')), 
                'allow_add' => true,
                'allow_delete' => true,
                'attr'=>array('class'=>'form_collection clearfix')
            ))
        ->add('subpage', 'entity', array(
                'class' => 'models\Page',
                'required' => false,
                'property' => 'title',
                'placeholder' => '-- Main Page --',
                'query_builder' => function (EntityRepository $er) {

                        return $er->createQueryBuilder('p')
                            ->where('p.view_status != -1 and p.id != '.$this->id.'');
                    },
                'attr' => array('class'=>'form-control')
            ))
        ->add('view_status', 'choice', array(
                'choices' => array(5 => 'Actief', 2 => 'Niet Actief'),
                'expanded' => false,
                'attr' => array('class'=>'form-control')
            ))
    ;


}

public function getName()
{
    return 'page';
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'models\Page',
    ));
}
}

模型页面.php

<?php

namespace models;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
* @Entity @Table(name="pages")
**/
class Page
{
/** @Id @Column(type="integer") @GeneratedValue **/
public $id;

/** @Column(type="string", nullable=false) **/
public $title;

/** @Column(type="string", nullable=true) **/
public $slug;

/** @Column(type="text", nullable=true) **/
public $intro;

/**
 * @Assert\File(maxSize="6000000")
 */
private $file;

/**
 * @ManyToOne(targetEntity="Page")
 * @JoinColumn(name="subpage_of", referencedColumnName="id")
 **/
public $subpage;

/** @Column(type="text", nullable=true) **/
public $text;

/** @Column(type="integer", nullable=false) **/
public $view_status;

/** @Column(type="datetime", nullable=true) **/
protected $pub_date;

/** @Column(type="datetime", nullable=true) **/
public $chg_date;

/**
 * @ManyToMany(targetEntity="models\Tag", cascade={"persist"})
 */
protected $tags;

/**
 * @Column(type="string", length=255, nullable=true)
 */
public $path;

public function __toString()
{
    return (string) $this->getTitle();
}

public function __construct()
{
    $this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}

public function upload()
{
    die();
    // the file property can be empty if the field is not required
    if (null === $this->getFile()) {
        return;
    }

    // use the original file name here but you should
    // sanitize it at least to avoid any security issues

    // move takes the target directory and then the
    // target filename to move to
    $this->getFile()->move(
        $this->getUploadRootDir(),
        $this->getFile()->getClientOriginalName()
    );

    // set the path property to the filename where you've saved the file
    $this->path = $this->getFile()->getClientOriginalName();

    // clean up the file property as you won't need it anymore
    $this->file = null;
}

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()
{
    // the absolute directory path where uploaded
    // documents should be saved
    return __DIR__.'/../../../../web/'.$this->getUploadDir();
}

protected function getUploadDir()
{
    // get rid of the __DIR__ so it doesn't screw up
    // when displaying uploaded doc/image in the view.
    return 'uploads/documents';
}


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

/**
 * Sets file.
 *
 * @param UploadedFile $file
 */
public function setFile(UploadedFile $file = null)
{
    $this->file = $file;
}

/**
 * Get file.
 *
 * @return UploadedFile
 */
public function getFile()
{
    return $this->file;
}

/**
 * Set title
 *
 * @param string $title
 *
 * @return Page
 */
public function setTitle($title)
{
    $this->title = $title;

    return $this;
}

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

/**
 * Set slug
 *
 * @param string $slug
 *
 * @return Page
 */
public function setSlug($slug)
{
    $this->slug = $slug;

    return $this;
}

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

/**
 * Set intro
 *
 * @param string $intro
 *
 * @return Page
 */
public function setIntro($intro)
{
    $this->intro = $intro;

    return $this;
}

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

/**
 * Set photo
 *
 * @param string $photo
 *
 * @return Page
 */
public function setPhoto($photo)
{
    $this->photo = $photo;

    return $this;
}

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

/**
 * Set text
 *
 * @param string $text
 *
 * @return Page
 */
public function setText($text)
{
    $this->text = $text;

    return $this;
}

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

/**
 * Set viewStatus
 *
 * @param integer $viewStatus
 *
 * @return Page
 */
public function setViewStatus($viewStatus)
{
    $this->view_status = $viewStatus;

    return $this;
}

/**
 * Get viewStatus
 *
 * @return integer
 */
public function getViewStatus()
{
    return $this->view_status;
}

/**
 * Set pubDate
 *
 * @param \DateTime $pubDate
 *
 * @return Page
 */
public function setPubDate($pubDate)
{
    $this->pub_date = $pubDate;

    return $this;
}

/**
 * Get pubDate
 *
 * @return \DateTime
 */
public function getPubDate()
{
    return $this->pub_date;
}

/**
 * Set chgDate
 *
 * @param \DateTime $chgDate
 *
 * @return Page
 */
public function setChgDate($chgDate)
{
    $this->chg_date = $chgDate;

    return $this;
}

/**
 * Get chgDate
 *
 * @return \DateTime
 */
public function getChgDate()
{
    return $this->chg_date;
}

/**
 * Set subpage
 *
 * @param \models\Page $subpage
 *
 * @return Page
 */
public function setSubpage(\models\Page $subpage = null)
{
    $this->subpage = $subpage;

    return $this;
}

/**
 * Get subpage
 *
 * @return \models\Page
 */
public function getSubpage()
{
    return $this->subpage;
}

/**
 * Add tag
 *
 * @param \models\Tag $tag
 *
 * @return Page
 */
public function addTag(\models\Tag $tag)
{
    $this->tags[] = $tag;

    return $this;
}

/**
 * Remove tag
 *
 * @param \models\Tag $tag
 */
public function removeTag(\models\Tag $tag)
{
    $this->tags->removeElement($tag);
}

/**
 * Get tags
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getTags()
{
    return $this->tags;
}

/**
 * Set path
 *
 * @param string $path
 *
 * @return Page
 */
public function setPath($path)
{
    $this->path = $path;

    return $this;
}

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

提交后的值

    object(stdClass)#327 (13) {
  ["__CLASS__"]=>
  string(11) "models\Page"
  ["id"]=>
  int(66)
  ["title"]=>
  string(4) "mama"
  ["slug"]=>
  NULL
  ["intro"]=>
  NULL
  ["file"]=>
  NULL
  ["subpage"]=>
  object(stdClass)#493 (15) {
    ["__CLASS__"]=>
    string(11) "models\Page"
    ["__IS_PROXY__"]=>
    bool(true)
    ["__PROXY_INITIALIZED__"]=>
    bool(true)
    ["id"]=>
    int(65)
    ["title"]=>
    string(4) "hans"
    ["slug"]=>
    NULL
    ["intro"]=>
    NULL
    ["file"]=>
    NULL
    ["subpage"]=>
    NULL
    ["text"]=>
    NULL
    ["view_status"]=>
    int(5)
    ["pub_date"]=>
    string(8) "DateTime"
    ["chg_date"]=>
    string(8) "DateTime"
    ["tags"]=>
    string(8) "Array(0)"
    ["path"]=>
    NULL
  }
  ["text"]=>
  NULL
  ["view_status"]=>
  int(5)
  ["pub_date"]=>
  object(stdClass)#575 (3) {
    ["__CLASS__"]=>
    string(8) "DateTime"
    ["date"]=>
    string(25) "2015-07-31T16:17:44+02:00"
    ["timezone"]=>
    string(13) "Europe/Berlin"
  }
  ["chg_date"]=>
  object(stdClass)#557 (3) {
    ["__CLASS__"]=>
    string(8) "DateTime"
    ["date"]=>
    string(25) "2015-07-31T16:27:39+02:00"
    ["timezone"]=>
    string(13) "Europe/Berlin"
  }
  ["tags"]=>
  array(2) {
    [0]=>
    string(10) "models\Tag"
    [1]=>
    string(10) "models\Tag"
  }
  ["path"]=>
  NULL
}

有谁知道为什么会出现这个错误?

【问题讨论】:

  • 只是为了确保在调用 $form->handleRequest() 之前从您的控制器发布 var_dump($_REQUEST); 的结果。
  • 标准File 表单类型中没有file_pathfile_name 选项。您是否使用自定义表单类型?
  • 文件输入好像不行。我仍然不知道如何解决这个问题
  • @lazypanda 您的表单是否在enctype='multipart/form-data' 支持下呈现?参考w3schools.com/tags/att_form_enctype.asp
  • @lazypanda 发送文件到服务器你的打开表单标签应该有这个属性并且你的请求方法应该是 post

标签: symfony doctrine-orm symfony-forms silex


【解决方案1】:

我有同样的错误信息,发现表单没有 enctype='multipart/form-data'。

通过将其添加到表单标签中,问题得到解决。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2019-12-09
    • 1970-01-01
    相关资源
    最近更新 更多