Symfony2上传/无法保存到文件夹

时间:2015-08-05 14:26:55

标签: symfony doctrine-orm upload

你能帮我解决这个问题吗? 我尝试了本教程:Symfony Upload

它工作正常(存储到img的数据库路径),但不要将图像存储或移动到文件夹。

实体:

    <?php
namespace DbBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;


/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class File
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    public $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    public $name;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    public $path;

    /**
     * @Assert\File(maxSize="6000000")
     */
    private $file;

    private $temp;

    /**
     * Sets file.
     *
     * @param UploadedFile $file
     */
    public function setFile(UploadedFile $file = null)
    {
        $this->file = $file;
        // check if we have an old image path
        if (isset($this->path)) {
            // store the old name to delete after the update
            $this->temp = $this->path;
            $this->path = null;
        } else {
            $this->path = 'initial';
        }
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        if (null !== $this->getFile()) {
            // do whatever you want to generate a unique name
            $filename = sha1(uniqid(mt_rand(), true));
            $this->path = $filename.'.'.$this->getFile()->guessExtension();
        }
    }

    /**
     * Get file.
     *
     * @return UploadedFile
     */
    public function getFile()
    {
        return $this->file;
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
        if (null === $this->getFile()) {
            return;
        }

        // if there is an error when moving 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->getFile()->move($this->getUploadRootDir(), $this->path);

        // check if we have an old image
        if (isset($this->temp)) {
            // delete the old image
            unlink($this->getUploadRootDir().'/'.$this->temp);
            // clear the temp image path
            $this->temp = null;
        }
        $this->file = null;
    }

    /**
     * @ORM\PostRemove()
     */
    public function removeUpload()
    {
        $file = $this->getAbsolutePath();
        if ($file) {
            unlink($file);
        }
    }

    public function getAbsolutePath()
    {
        return null === $this->path
            ? null
            : $this->getUploadRootDir().'/'.$this->path;
    }

    public function getWebPath()
    {
        return null === $this->path
            ? null
            : $this->getUploadDir().'/'.$this->path;
    }

    protected function getUploadRootDir()
    {
        // the absolute directory path where uploaded
        // documents should be saved
        return __DIR__.'/../../../../web/'.$this->getUploadDir();
    }

    protected function getUploadDir()
    {
        // get rid of the __DIR__ so it doesn't screw up
        // when displaying uploaded doc/image in the view.
        return 'uploads/documents';
    }
}

控制器

    public function uploadAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $document = new File();
        $form = $this->createFormBuilder($document)
            ->add('name')
            ->add('file')
            ->getForm();

        $form->handleRequest($request);
        if ($form->isValid()) {
            $em->persist($document);
            $em->flush();

            return $this->redirectToRoute('web_portal_file');
        }


        return $this->render('WebPortalBundle:Default:file.html.twig',array('file_form' => $form->createView()));
    }

编辑:Twig:

 <form action="{{ path('web_portal_file') }}" method="post" {{ form_enctype(file_form) }}>
    {{ form_widget(file_form.file) }}
    {{ form_rest(file_form) }}
    <input type="submit"/>
</form>

我不知道如何做到这一点。每次路径保存到数据库,但文件夹为空......

2 个答案:

答案 0 :(得分:2)

请记住上传文件将以表格标签数据加密:PHP method uploads

在Symfony2中,Twig将是:


    form class="" action="" method="post" {{ form_enctype(file_form) }}
       {{ form_widget(file_form) }}
    /form

答案 1 :(得分:0)

问题可能在这里。 在控制器上。当你持久化实体时,你调用upload()方法


    if($form->isValid()) {

       $em->persist($document);       
       $em->flush();

       return $this->redirectToRoute('web_portal_file');
    }

在CookBook中说:

前一个控制器将自动使用提交的名称保留Document实体,但它不会对该文件执行任何操作,并且path属性将为空。

处理文件上传的一种简单方法是在实体持久化之前移动它,然后相应地设置路径属性。首先在Document类上调用一个新的upload()方法,稍后您将创建该方法来处理文件上载:

立即


    if($form->isValid()) {

         $document->upload();
         $em->persist($document);
         $em->flush();

         return $this->redirectToRoute('web_portal_file');
    }