Symfony 2.2上传文件 [英] Symfony 2.2 upload files
本文介绍了Symfony 2.2上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
自从我使用Symfony2上传文件以来,已经有一段时间了,似乎一切都已改变,请遵循如何使用Doctrine处理文件上传,但已过时且不起作用.
It's been a while since I uploaded files with Symfony2 and it seems that everything has changed, follow the guide in How to handle File Uploads with Doctrine but is outdated and dont work.
当我尝试将表格绑定时出现错误
when i try to bind the form a get a error
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';
}
}
推荐答案
在完美完成添加工作后,我忘记在表单中添加enctype
I forget add enctype to my form after added work perfectly
<form action="{{ path('documento_upload') }}" method="post" {{ form_enctype(upload_form) }}>
{{ form_widget(upload_form) }}
<button type="submit" class="btn btn-primary">Upload</button>
</form>
这篇关于Symfony 2.2上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文