2017-01-17 3 views
0

UploadImageBehaviorに問題があります。Yii2 UploadImageBehavior。ファイルを削除するには?

モデル保存後に画像(ユーザーアバター)を削除できるように、フロントエンド部分に単純なボタンを作成する必要があります。 実際には私はunlinkでそれを行う方法を知っていますが、私は絶対に動作によってそれを行う方法を理解していません。

私は、ルール内の次のコードを持っている:私は私のアバタープロパティにnullを渡そうだから、Yiiのはちょうど、私を無視

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

を。

Thxを)

答えて

0

ただ、リンク解除を行い、あなたのモデルクラスにメソッドを作成し、nullにモデル内のファイルの属性を設定し、モデルを保存します。

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

です
関連する問題