6
我上传Symfony2文件已经有一段时间了,似乎所有内容都已更改,请按照How to handle File Uploads with Doctrine中的指南进行操作,但已过时并且不工作。Symfony 2.2上传文件
当我尝试绑定的形式得到了错误
Catchable Fatal Error: Argument 1 passed to Entity\Portada::setFile() must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile, string given, ...
这是我的控制器
/**
* @Route("/upload", name="documento_upload")
* @Method("POST")
* @Template()
*/
public function uploadAction(Request $request)
{
$portada = new Portada();
$form = $this->buildUploadForm($portada);
$form->bind($request);
if ($form->isValid()) {
$portada->upload();
} else {
throw new \Exception("Hay un error en el formulario");
}
//...
}
我的实体
<?php
namespace MyName\MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
class Portada
{
/**
* @Assert\File(maxSize="6000000")
*/
private $file;
public $path;
/**
* Sets file.
*
* @param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
}
public function upload()
{
$this->path = $this->getFile()->getClientOriginalName();
$this->getFile()->move(
$this->getUploadRootDir(),
$this->path
);
$this->file = null;
}
/**
* Get file.
*
* @return UploadedFile
*/
public function getFile()
{
return $this->file;
}
public function getAbsolutePath()
{
return null === $this->path
? null
: $this->getUploadRootDir() . DIRECTORY_SEPARATOR . $this->path;
}
public function getWebPath()
{
return null === $this->path
? null
: $this->getUploadDir() . DIRECTORY_SEPARATOR . $this->path;
}
protected function getUploadRootDir()
{
return __DIR__ . '/../../../../web/'. $this->getUploadDir();
}
protected function getUploadDir()
{
return 'uploads/portada';
}
}
+1 aaaaahhhhh ....谢谢:) – 2013-04-22 18:31:06
有没有可能做到这一点没有形式建设者? – Gigala 2013-06-06 10:11:08
@Gigala这是可能的,但我不试试。检查'$ this-> getRequest() - > files'返回一个FileBag,你可以检查如何移动withut使用形式 – rkmax 2013-06-06 15:05:12