在Symfony中提交表单后命名文件


naming a file after submitting a form in Symfony

我正在处理一个接受一些用户输入和图像文件的表单,提交部分和输入数据库的数据工作正常,但我被困在上传文件后如何命名文件,现在这就是我在数据库中看到的图像名称C:'wamp2.5'tmp'phpF360.tmp这显然不正确。

这就是我的控制器的样子DefaultController.php

public function createBlogAction(Request $request)
{
    $post = new Post();
    $form = $this->createForm(new PostCreate(), $post);
    $form->handleRequest($request);
    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $post->upload();
        $post->setDate(date_create(date('Y-m-d H:i:s')));
        $post->setAuthor('ClickTeck');
        $em->persist($post);
        $em->flush();
        $this->get('session')->getFlashBag()->add(
            'notice',
            'Success'
        );
    }
    return $this->render('BlogBundle:Default:blog-create.html.twig', array(
            'form' => $form->createView()
        )
    );
}

这就是我的upload()Entity/Post.php中的样子,它正在上传文件并将其移动到文件夹中,我在文件夹中看到的文件名是正确的,但是现在进入数据库的文件名

是正确的
public function upload()
{
    if (null === $this->getImage()) {
        return;
    }
    // I might be wrong, but I feel it is here that i need to name the file
    $this->getImage()->move(
        $this->getUploadRootDir(),
        $this->getImage()->getClientOriginalName()
    );
    $this->path = $this->getUploadDir();
    $this->file = null;
}

如果有人能把我推向正确的方向,我将不胜感激,我只需要命名文件,一个分配给数据库中图像的名称,文件也应该以相同的名称上传。


更新

我设法使用以下功能使其工作,不确定这是否是最佳实践,但它确实有效,我很想听听其他人的意见。 请不要提供任何链接,如果您可以完善已经完成的工作,那就太好了。

public function upload()
{
    // the file property can be empty if the field is not required
    if (null === $this->getImage()) {
        return;
    }
    $dirpath = $this->getUploadRootDir();
    $image = $this->getImage()->getClientOriginalName();
    $ext = $this->getImage()->guessExtension();
    $name = substr($image, 0, - strlen($ext));
    $i = 1;
    while(file_exists($dirpath . '/' .  $image)) {
        $image = $name . '-' . $i .'.'. $ext;
        $i++;
    }
    $this->getImage()->move($dirpath,$image);
    $this->image = $image;
    $this->path = $this->getUploadDir();
    $this->file = null;
}

文档中的本主题可能会对您有所帮助: http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html

此外,您不应将上传函数放在控制器中,而应使用 Doctrine 事件(生命周期回调(自动调用函数。

根据

@theofabry的建议,您可以查看Symfony2文档 如何使用原则处理文件上传,控制器必须尽可能瘦,并尝试使用Doctrine Events进行上传。

如果你想继续你的逻辑,你可以尝试以下代码,我还没有测试过......所以请小心。

   // set the path property to the filename where you'ved saved the file
   $this->path = $this->file->getClientOriginalName();

而不是

 $this->path = $this->getUploadDir();