Yii2 UploadImageBehavior。如何删除文件?

时间:2017-01-17 21:16:10

标签: yii yii2 image-uploading

我对UploadImageBehavior有疑问。

我需要在前端部分创建一个简单的按钮,允许我在模型保存后删除图像(用户头像)。 实际上我知道怎么用unlink来做,但我绝对不了解如何通过行为来做到这一点。

我在规则中有下一个代码:

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

所以如果我试图将null传递给我的头像属性,Yii就会忽略我。

Thx)

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:0)

以下对我有用:

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

getcwd()获取当前工作目录。它的文档是here