Jigar KarangiyaJigar Karangiya

How to delete file in magento 2 programmatically

JK
Jigar Karangiya
· 1 min read
How to delete file in magento 2 programmatically

Hello Magento Devs,

In today’s tutorial, i’m going to show you how you can delete file in magento 2 programatically.

Method 1 : Using injecting class in constructor

We can delete file in magento standard way by injecting below class in constructor.

text
\Magento\Framework\Filesystem\Driver\File $file

Let’s understand it by a simple example.

php
<?php
namespace Jigar/DeleteTutorial/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= "your_filename.csv";
        $mediaRootDir = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
        if ($this->file->isExists($mediaRootDir . $fileName)) {
            $this->file->deleteFile($mediaRootDir . $fileName);
        }
       
    }
}

Method 2 : Directly using object manager (Not Recommended)

php
$fileName= "your_filename.csv";
 
$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);
}

That’s it, now you know how to delete any file in magento standard way.

Thanks for reading !!

Written by Jigar Karangiya, Adobe Commerce & Magento 2 developer.

More about me

Related posts