如何从控制器中删除照片或使用 cakephp-upload 查看

How to delete photos from controller or view with cakephp-upload

我正在关注cakephp-upload tutorial and everything works out well. However, there is no documentation on how to delete files except for this, which doesn't really help me out.

我想我必须创建一个控制器函数才能这样做,但这是我目前所能做到的。

我计划创建一个包含已上传个人资料照片的视图,以及一个用于将其从视图中删除的删除按钮。

有什么功能性的例子可以帮我找一下吗?

编辑:一切正常!...除了将我的 photo 字段设置为空。我已经检查了 ->allowEmpty('photo', 'create')->allowEmpty('photo', 'update') 的验证器。我 运行 没有想法,但我会提出一个新问题来保持秩序。非常感谢!

    if ($this->request->is(['patch', 'post', 'put'])) {
        $brigada = $this->Brigadas
                    ->findById($id)
                    ->firstOrFail();       
        $file = WWW_ROOT . 'files/Brigadas/photo' . $brigada->photo_dir . '/' . $brigada->photo;
        if(file_exists($file)) {
            unlink($file);
        }
        $brigada->dir = null;
        $brigada->photo = null;
        $this->Brigadas->save($brigada);
    }

您可以使用文件夹和 File utilities

$file = new File(WWW_ROOT.'/img/'.$user->image);
$file->delete();

我认为您不需要插件来删除文件。 只需检查该文件是否存在,否则您将看到所有错误,最后删除该文件。 例如以下代码(在您的控制器中):

if(file_exists(<your_url_img>)) {
  unlink(<your_url_img>);
}