2017-01-17 79 views
0

我有UploadImageBehavior問題。Yii2 UploadImageBehavior。如何刪除文件?

我需要創建前端的部分,讓我的模型保存後刪除圖像(頭像),簡單的按鈕。 其實我知道如何與unlink做到這一點,但我絕對不知道怎麼做,通過行爲。

我在接下來的規則代碼:

[['avatar'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg'],

所以Yii的不理我,如果我試圖通過null我的頭像財產。

THX)

回答

0

只需創建你的模型類的方法,做取消鏈接,將在你的模型爲空文件屬性並保存模型。

public function removeAvatar() { 
    $transaction = $this->getDb()->beginTransaction(); 
    try { 
     // If this is a new record throw an Exception because no file has been uploaded yet 
     if($this->isNewRecord) { 
      throw new \Exception("Can't delete file of new record"); 
     } 

     // Set the attribute avatar to null 
     $this->avatar = null; 

     // Try to save the record. If we can't then throw an Exception 
     if(!$this->save()) { 
      throw new \Exception("Couldn't save the model"); 
     } 

     // Try to delete the file. If we can't then throw an Exception 
     if(!unlink(Yii::getAlias('@app/path/to/your/file.something')) { 
      throw new \Exception("Couldn't delete the file"); 
     } 

     $transaction->commit(); 
     return true; 
    } 
    catch(\Exception $e) { 
     $transaction->rollback(); 
     return false; 
    } 
} 
0

下面爲我工作:

unlink(getcwd().'/uploads/'.$model->file_id.'/'.$fileModel->file_name.$fileModel->extension); 

GETCWD()獲取當前工作目錄。它的文檔是here