Magento 2: how to delete image or file
Very important question as in my experience, when submitting an extension for marketplace, the validation generated errors regarding using of such method directly. I've researched and found following solution.
inject this \Magento\Framework\Filesystem\Driver\File $file
in your constructor
(make sure to declare class level variable i.e, protected $_file;
)
and then you can have access to the methods which includes: isExists
and deleteFile
for example: in constructor
public function __construct(\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Filesystem\Driver\File $file){
$this->_file = $file;
parent::__construct($context);
}
and then in the method where you're trying to delete a file:
$mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
$mediaRootDir = $mediaDirectory->getAbsolutePath();
if ($this->_file->isExists($mediaRootDir . $fileName)) {
$this->_file->deleteFile($mediaRootDir . $fileName);
}
hope this helps.
The answer of RT is good, but we should not use the ObjectManager directly in the example.
The reason is here "Magento 2: to use or not to use the ObjectManager directly".
So better example is below:
<?php
namespace YourNamespace;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
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(
Context $context,
Filesystem $_filesystem,
File $file
)
{
parent::__construct($context);
$this->_filesystem = $_filesystem;
$this->_file = $file;
}
public function execute()
{
$fileName = "imageName";// replace this with some codes to get the $fileName
$mediaRootDir = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
if ($this->_file->isExists($mediaRootDir . $fileName)) {
$this->_file->deleteFile($mediaRootDir . $fileName);
}
// other logic codes
}
}