Skip to content

Enhancement - Delete file during/after edit #493

@stosh15x

Description

@stosh15x

Hi I recently noticed an issue that files where not being deleted when I was editing a table. (IE: User changes their profile photo.) I have the plugin uploading the file, updating the database but the old file doesn't get deleted.

Note:
I changed the path in the config to:

'path' => 'webroot{DS}img{DS}{model}{DS}{field}{DS}'

So here is my temporary solution in the model but I imagine there is a better way to accomplish this.

use Cake\Filesystem\File;
use Cake\Event\Event;
use Cake\ORM\Entity;
use ArrayObject;

// clean up default leaderboard image change
public function afterSave(Event $event, Entity $entity, ArrayObject $options) {
  $field = 'image';

  $original = $entity->getOriginal($field);
  if($entity->{$field} != $original && $original != null) {
    $path = ROOT . DS . $entity->image_dir . $original;
    $file = new File($path);
    if($file->exists()) {
       $file->delete();
    }
    $file->close();
  }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions