我在尝试使用Symfony2.3上传单个文件时遇到了问题。当我尝试上传文件时,出现以下错误:
FatalErrorException: Error: Call to a member function move() on a non-object in
我已检查$csvFileForm['csvFile']->getData();
及其字符串(文件名称),$file = $this->getRequest()->files;
的大小为零。
以下是节目动作:
/**
* Finds and displays a Project entity.
*
* @Route("/{id}", name="console_project_show")
* @Method("GET")
* @Template()
*/
public function showAction($id)
{
$csvFileForm = $this->createFormBuilder()
->add('csvFile', 'file')
->getForm();
return array(
'csvFileForm' => $csvFileForm->createView()
);
}
,模板中的表单如下所示:
<form method="POST" action="{{ path('console_project_upload_urls', { 'id': entity.id }) }}" >
{{ form_row(csvFileForm.csvFile) }}
{{ form_row(csvFileForm._token) }}
<input type="submit" name="submit" class="submit"/>
</form>
上传操作是:
/**
* Lists all Project entities.
*
* @Route("/{id}/upload-urls", name="console_project_upload_urls")
* @Method("POST")
*/
public function uploadUrlsAction(Request $request, $id)
{
$csvFileForm = $this->createFormBuilder()
->add('csvFile', 'file')
->getForm();
$request = $this->getRequest();
$csvFileForm->handleRequest($request);
$data = $csvFileForm['csvFile']->getData();
$data->move(".", "something.csv"); // This is where the exception occurs
$file = $this->getRequest()->files; // I have used this to check the size of the array
return $this->redirect(...);
}
感谢您的帮助。
答案 0 :(得分:9)
您必须将enctype添加到表单标记。
<form method="POST" action="{{ path('console_project_upload_urls', { 'id': entity.id }) }}" {{ form_enctype(form) }}>
...
</form>
注意:从Symfony2.3开始不推荐使用此功能,将在Symfony3中删除。您应该使用新的form_start() twig helper。
{{ form_start(form, {'method': 'POST', 'action': path('console_project_upload_urls', { 'id': entity.id })}) }}
...
{{ form_end(form) }}