[英]File uploads in Symfony 2 using sonata-project
I am trying to upload a image in Symfony 2 from the backend using sonata-project. 我正在尝试使用sonata-project从后端在Symfony 2中上传图像。 Challenge that i'm facing right now is to get the image inserted into the database table and uploaded to the specified path. 我现在面临的挑战是将图像插入数据库表并上传到指定的路径。 I have given my upload folder writeable permissions. 我已授予我的上载文件夹可写权限。 I am not sure what i am missing but here are the steps that i have taken. 我不确定我缺少什么,但是这里是我已采取的步骤。
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;
}
} }
I have edited my HomeEnumerate.orm.yml i have put in lifecycleCallbacks: 我已经编辑了生命周期回调的HomeEnumerate.orm.yml:
lifecycleCallbacks:
prePersist: [ preUpload, setCreatedAtValue, setExpiresAtValue ]
preUpdate: [ preUpload, setUpdatedAtValue ]
postPersist: [ upload ]
postUpdate: [ upload ]
postRemove: [ removeUpload ]
After generate:entities I have edited my HomeEnumerate entity 在generate:entities之后,我已经编辑了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);
}
}
}
} }
Can someone please help me uploading the files to the db and folder path. 有人可以帮我将文件上传到数据库和文件夹路径吗?
You should implement some callbacks in your admin class, too. 您也应该在管理类中实现一些回调。 Actually, SonataAdminBundle has a cookbook recipe on handling file uploads . 实际上,SonataAdminBundle具有处理文件上传的食谱 。 Hopefully, it should answer all of your questions. 希望它可以回答您所有的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.