我正在尝试使用sonata-project从后端上传Symfony 2中的图像。我现在面临的挑战是将图像插入数据库表并上传到指定路径。我已经为我的上传文件夹写了可写权限。我不知道我错过了什么,但这是我采取的步骤。
class HomeEnumerate
{
// ...
protected function getUploadDir()
{
return 'uploads/houses';
}
protected function getUploadRootDir()
{
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
public function getWebPath()
{
return null === $this->house_picture ? null : $this->getUploadDir().'/'.$this->house_picture;
}
public function getAbsolutePath()
{
return null === $this->house_picture ? null : $this->getUploadRootDir().'/'.$this->house_picture;
}
}
我已经编辑了我的HomeEnumerate.orm.yml,我已经放入了lifecycleCallbacks:
lifecycleCallbacks:
prePersist: [ preUpload, setCreatedAtValue, setExpiresAtValue ]
preUpdate: [ preUpload, setUpdatedAtValue ]
postPersist: [ upload ]
postUpdate: [ upload ]
postRemove: [ removeUpload ]
生成:我编辑了HomeEnumerate实体的实体
class Job
{
// ...
/**
* @ORM\PrePersist
*/
public function preUpload()
{
if (null !== $this->file) {
$this->logo = uniqid().'.'.$this->file->guessExtension();
}
}
/**
* @ORM\PostPersist
*/
public function upload()
{
if (null === $this->file) {
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->file->move($this->getUploadRootDir(), $this->logo);
unset($this->file);
}
/**
* @ORM\PostRemove
*/
public function removeUpload()
{
if(file_exists($file)) {
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
}
}
有人可以帮我上传文件到数据库和文件夹路径。
答案 0 :(得分:0)
您也应该在管理类中实现一些回调。实际上,SonataAdminBundle有a cookbook recipe on handling file uploads。希望它能回答你所有的问题。