我想让文件名看起来像:Username-OriginalFileName。我的第一个解决方案是在我的文件实体中使用preUpload回调,如 Symfony 食谱中所述
/**
* @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 上传。我究竟做错了什么?