在文件上载时生成包含文件用户名的文件名

时间:2012-04-16 20:24:47

标签: symfony doctrine-orm symfony-forms

我希望文件名看起来像:Username-OriginalFileName。 我的第一个解决方案是在我的文件实体中使用preUpload回调,如Symfony cookbook here

中所述
  /**
  * @Assert\File(maxSize="6000000")
   */
 public $FILE_file;

 public $path;

    public function getPath()
    {
        return $this->path;
    }
    public function setPath($path)
    {
        return $this->path=$path;
    }

    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()
    {
        return __DIR__.'/../../../../web/'.$this->getUploadDir();
    }

    protected function getUploadDir()
    {

        return 'uploads/files';
    }


    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */

    public function preUpload()
    {
        if (null !== $this->FILE_file) {
                      $username=$this->get('security.context')->getToken()->getUser()->getUsername();
            $this->path = $username.'-'.$this->path;
        }
    }

     /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */

        public function upload()
    {
        // the file property can be empty if the field is not required
        if (null === $this->FILE_file) {
            return;
        }

        $this->FILE_file->move($this->getUploadRootDir(),  $this->FILE_file->getClientOriginalName());

        $this->path = $this->FILE_file->getClientOriginalName();

        $this->FILE_file = null;
    }

但似乎我无法从实体获取容器。 所以我试图在我的文件控制器中执行此操作:

                          $filename=$username.'-'.$file->path;

                            $file->setPath($filename);      
                            $file->setFILEFormat($ext);
                           ...

                            $em1->persist($file); 
                            $em1->flush();
                            $file->upload();
                            $content=$file->getContent();

getContent是一个打开文件并将其内容存储在字符串数组中的函数。由于某种原因,文件是持久的,并使用其上传表单中的OriginalName上传,而不是使用$ filename。我做错了什么?

1 个答案:

答案 0 :(得分:2)

文件与用户之间是否存在任何关系? 否则你可以这样做:

文件实体:

/**
 *
 * @ORM/ManyToOne(targetEntity="User" …)
 */
private $user;

public function preUpload()
{
    if (null !== $this->FILE_file) {
        $this->path = $this->user->getUsername().'-'.$this->path;
    }
}