简体   繁体   中英

Symfony 4 : How to delete a file from folder using remove function of the filesystem component

I am trying to remove a file from folder using remove function of the filesystem component in Symfony 4.

Here is my code in the controller:

//Get old logo
$oldlogo = $employer->getLogo();
//If there is a old logo we need to detele it
     if($oldlogo){
       $filesystem = new Filesystem();
       $path=$this->getTargetDirectory().'/public/uploads/logos/'.$oldlogo;
       $filesystem->remove($path);
 }

private $targetDirectory;

public function __construct($targetDirectory)
    {
        $this->targetDirectory = $targetDirectory;
    }

public function getTargetDirectory()
    {
        return $this->targetDirectory;
    }

Service.yalm:

parameters:
    logos_directory: '%kernel.project_dir%/public/uploads/logos'

App\Controller\EmployerController:
        arguments:
            $targetDirectory: '%logos_directory%'

I have no error message but the file not deleted from the folder.

I using this solution:

in my services.yaml I add:

public_directory: '%kernel.project_dir%/public'

and in my controller I use

$filesystem = new Filesystem();
$path=$this->getParameter("public_directory").'/uploads/logos/'.$oldlogo;
$filesystem->remove($path);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM