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.
1 |
\Magento\Framework\Filesystem\Driver\File $file |
Let’s understand it by a simple example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?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)
1 2 3 4 5 6 7 8 9 |
$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 !!