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);
}

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply