簡體   English   中英

使用Sonata-project在Symfony 2中上傳文件

[英]File uploads in Symfony 2 using sonata-project

我正在嘗試使用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:
    prePersist: [ preUpload, setCreatedAtValue, setExpiresAtValue ]
    preUpdate: [ preUpload, setUpdatedAtValue ]
    postPersist: [ upload ]
    postUpdate: [ upload ]
    postRemove: [ removeUpload ]

在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);
        }
    }    
}

}

有人可以幫我將文件上傳到數據庫和文件夾路徑嗎?

您也應該在管理類中實現一些回調。 實際上,SonataAdminBundle具有處理文件上傳的食譜 希望它可以回答您所有的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM