symfony2文件上传

Bou*_*uki 8 upload symfony

我遵循了这个指南:http://symfony.com/doc/current/reference/forms/types/file.html

并在这里测试了样本

但是,当我尝试代码时,我有一个错误:

Call to undefined method Symfony\Component\Form\Form::move()
Run Code Online (Sandbox Code Playgroud)

线路正在发生这种情况:

$form['attachment']->move($dir, $someNewFilename);
Run Code Online (Sandbox Code Playgroud)

我想知道为什么会出现这个错误?

小智 18

这不使用'Form'类,但我已成功直接从请求中检索上传:

/* @var Request */
$request = $this->getRequest();

/* @var UploadedFile */
$uploadedFile = $request->files->get('upfile'); //upfile must be the value of the name attribute in the <input> tag
if (null === $uploadedFile)
    return new RedirectResponse($this->generateUrl('_upload_index'));

/* @var string*/
$filename = $uploadedFile->getPathname();
Run Code Online (Sandbox Code Playgroud)


Bou*_*uki 17

我终于找到了解决方案

该文档是错误的

代替 :

$form['attachment']->move($dir, $someNewFilename);
Run Code Online (Sandbox Code Playgroud)

它应该是 :

$form['attachment']->getData()->move($dir, $someNewFilename);
Run Code Online (Sandbox Code Playgroud)

  • 啊,我有一个硬编码的<form>标签,并没有添加enctype ="multipart/form-data"属性; 添加,返回UploadedFile对象而不是字符串! (2认同)

Max*_*ooo 5

现在最好按照官方文档中的说明进行操作:http: //symfony.com/doc/2.0/cookbook/doctrine/file_uploads.html