Site icon Qaisar Satti's Blogs

Magento 2 delete file or image

Magento 2 delete file or image

Magento 2 delete file or image

Today we discuss how to delete a file or image in Magento 2. In this tutorial, we focus on Magento 2 ways to delete the file or image. As a PHP developer, you already about the function unlink(filepathhere) will delete the file for you. So let start with our example.

namespace QaisarSatti/HelloWorld/Block;

use Magento\Backend\App\Action;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;

class Delete extends Action
{

    protected $fileSystem;
    protected $file;

    public function __construct(
        Filesystem $fileSystem,
        File $file
    )
    {
        $this->fileSystem = $fileSystem;
        $this->file = $file;
    }

    public function delete()
    {
        $fileName= "helloworld.jpg";
        $mediaRootDir = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
        if ($this->file->isExists($mediaRootDir . $fileName)) {
            $this->file->deleteFile($mediaRootDir . $fileName);
        }
       
    }
}

Delete FIle with ObjectManager.

$fileName= "helloworld.jpg";
$file = $this->_objectManager->get('Magento\Framework\Filesystem\Driver\File');
$mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
$mediaRootDir = $mediaDirectory->getAbsolutePath();

if ($file->isExists($mediaRootDir . $fileName))  {

    $file->deleteFile($mediaRootDir . $fileName);
}
Exit mobile version