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.
\Magento\Framework\Filesystem\Driver\File $file
Let’s understand it by a simple example.
<?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)
$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 !!
Leave a Comment