Symfony2文件上传

8
我按照这个指南做了:http://symfony.com/doc/current/reference/forms/types/file.html 并在这里测试了示例
但是当我尝试运行代码时,出现了错误:
Call to undefined method Symfony\Component\Form\Form::move()

这是发生在这一行的事情:

$form['attachment']->move($dir, $someNewFilename);

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

3个回答

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();

17

我终于找到了解决方法

文档是错误的

应该是:

$form['attachment']->move($dir, $someNewFilename);

应该是:

$form['attachment']->getData()->move($dir, $someNewFilename);

使用Symfony 2.7(在Silex中),我目前发现->getData()仅返回文件名的字符串,因此->move()等无法对其起作用。 - J-P
2
啊,我在代码中硬编码了一个<form>标签,并且没有添加enctype="multipart/form-data"属性;添加后,返回的是UploadedFile对象而不是字符串! - J-P

5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接