php - 如何使用没有实体类的表单上传文件

标签 php symfony

我尝试使用没有实体类的表单上传文件。到目前为止没有运气。

  // Controller
  public function uploadAction() {
    $request = $this->getRequest();
    $form = $this->createFormBuilder()
            ->add('images', 'file') // If I remove this line data is submitted correctly
            ->add('dir', 'text')
            ->getForm();

    if ($request->getMethod() == 'POST') {
      $request = $this->getRequest();
      $form->bindRequest($request);

      $data = $form->getData();
      var_dump($data);
    }   
    else
      return $this->render('OverseerMainBundle:Default:form.html.twig', array(
          'form' => $form->createView(),
      )); 
  }

// form.html.twig
{% block body %}
<form action="{{ path('OverseerMainBundle_upload') }}" method="post" {{ form_enctype(form) }}>
    {{ form_widget(form) }}

    <input type="submit" />
</form>
{% endblock %}

到目前为止 var_dump 回显:

array(2) { ["images"]=> NULL ["dir"]=> NULL }

但是,如果我删除 ->add('images', 'file') 行,一切正常:

array(1) { ["dir"]=> string(4) "test" }

附言我已经检查了表单和属性 enctype="multipart/form-data" 的 html 代码。所以这不是问题。

最佳答案

我也希望这对其他人有帮助:

if ($form->isValid()) {
        $file = $form->get('file')->getData();
        $name = $file->getClientOriginalName();
        $dir = __DIR__.'/../../../../web/uploads';

        $file->move($dir, $name) ;
    }

关于php - 如何使用没有实体类的表单上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9129864/

相关文章:

php - Symfony 2.8 与 Oracle 数据库 - 标识符太长

windows - php composer.phar 更新不适用于 Symfony 安装

php - Symfony 上的 Paypal Rest API

c# - 法朗格 (PHP) : calling nested static C# classes

php - Zend 与 Symfony

Symfony2 : Reference string or an array in config yaml

javascript - 主干模型已保存,但向 HTTP 发送空数组

php - 您如何获取 Facebook 用户的信息并将其插入数据库?

PHP preg_match_all 搜索和替换

javascript - 使用 jQuery 重新加载 div 内容