如何使用CakePHP3删除目录中图片的硬拷贝

迪斯特罗姆

下面的代码已经可以手动删除了,我想获取确切的图像,就像下面一样

$file = new File(WWW_ROOT .'img/websites/image-todelete.jpg', false, 0777);

public function delete($id = null)
    {

    $this->request->allowMethod(['post', 'delete']);
    $website = $this->Websites->get($id);      

    if ($this->Websites->delete($website)) {  
      $file = new File(WWW_ROOT . 'img/websites/image-todelete.jpg', false, 0777);
          if($file->delete()) {
                $this->Flash->success(__('The website has been deleted.'));
           }

    } else {
        $this->Flash->error(__('The website could not be deleted. Please, try again.'));
    }
    return $this->redirect(['action' => 'index']);
}

如何制作此代码

$file = new File(WWW_ROOT . 'img/websites/image-todelete.jpg', false, 0777);

通用代码?如果我曾经删除过数据,那么在删除记录时,它应该会自动删除目录中的图像。

马诺哈尔线

您可以简单地做到这一点:

public function delete($id = null)
{

$this->request->allowMethod(['post', 'delete']);
$website = $this->Websites->get($id);      

// take destination just before deleting that
$destination= $website->destination;
if ($this->Websites->delete($website)) {  
  $file = new File($destination);
      if($file->delete()) {
            $this->Flash->success(__('The website has been deleted.'));
       }

} else {
    $this->Flash->error(__('The website could not be deleted. Please, try again.'));
   }
   return $this->redirect(['action' => 'index']);
}

还有你的保存方法:

public function add(){
 $website = $this->Websites->newEntity();

 if ($this->request->is('post')) {


        //$image_name        = uniqid().$this->request->data['image']['name'];
        $image_name        = $this->request->data['image']['name'];
        $image_tmp         = $this->request->data['image']['tmp_name'];
        $destination       = WWW_ROOT.'img'.DS.'websites'.DS.$image_name;
        move_uploaded_file($image_tmp, $destination);
        $this->request->data['image'] = $image_name;
        $this->request->data['destination'] = $destination;

        $website = $this->Websites->patchEntity($website, $this->request->data);

        if ($this->Websites->save($website)) {
            $this->Flash->success(__('Data has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__(' Please, try again.'));
        }
    }



  $this->set(compact('website'));
  $this->set('_serialize', ['website']);
}

不要忘记在表中添加字段“目的地”字段..

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章