有人可以指出我在这里缺少的东西吗?我目前正在将文件上传添加到表单中,但文件不会从tmp目录中移出。我没有收到任何错误,但图像没有复制并驻留在tmp目录中。我已经尝试设置图像所在的文件夹的权限,并修改getUploadDir()路径,但仍然没有运气。
web / bundles / bloggerblog符号链接。我认为问题在于我在getUploadDir中使用的路径,我是否使用来自(src / blogger / blogbundle / Resources / public / images)的路径,因此它是符号链接或使用(web / bundles / bloggerblog / images)文件夹?
当前代码:
实体
protected $file;
public function getUploadDir()
{
return '/bundles/bloggerblog/images';
}
public function getUploadRootDir()
{
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
public function getWebPath()
{
return null === $this->image ? null : $this->getUploadDir().'/'.$this->image;
}
public function getAbsolutePath()
{
return null === $this->image ? null : $this->getUploadRootDir().'/'.$this->image;
}
/**
* @ORM\PrePersist()
* @ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->file) {
// Generate a unique name
$this->image = uniqid().'.'.$this->file->guessExtension();
}
}
/**
* @ORM\PostPersist()
* @ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->file) {
return;
}
// If there is an error when removing the file, an exception will be automatically thrown by move().
// This will properly prevent the entity from being persisted to the database on error.
$this->file->move($this->getUploadRootDir(), $this->image);
unset($this->file);
}
/**
* @ORM\PostRemove()
*/
public function removeUpload()
{
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
控制器
public function createAction(Request $request)
{
$blog = new Blog();
$form = $this->createFormBuilder($blog)
->add('title', 'text')
->add('author', 'text')
->add('blog', 'textarea')
->add('image', 'file')
->add('tags', 'text')
->add('save', 'submit')
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()
->getManager();
$em->persist($blog);
$em->flush();
// return new Response('Blog was added successfully');
return $this->redirect($this->generateUrl('BloggerBlogBundle_homepage'));
}
$build['form'] = $form->createView();
return $this->render('BloggerBlogBundle:Blog:create.html.twig', $build);
}
的CreateForm
{% extends 'BloggerBlogBundle::layout.html.twig' %}
{% block title %}Add Blog{% endblock %}
{% block body %}
<h1>Add Blog</h1>
{% include 'BloggerBlogBundle:Blog:form.html.twig' with { 'form': form } %}
{% endblock %}
形式
<form action="{{ path('BloggerBlogBundle_blog_create') }}" method="post" {{ form_enctype(form) }} class="blogger">
{{ form_widget(form) }}
答案 0 :(得分:2)
问题出在控制器的createFormBuilder中。
而不是
->add('image', 'file')
需要
->add('file', 'file', array(
'label' => 'Image',
'required' => false
))
然后一切都像魅力一样,很高兴我花了几个小时寻找答案并不是徒劳。