how to delete file or image in magento 2. I know using unlink('full file path'); will delete the file but I want to do magento 2 way. condition when User checked the delete checkbox.
Asked
Active
Viewed 1.3k times
10
Qaisar Satti
- 32,469
- 18
- 85
- 137
2 Answers
17
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.
R T
- 1,347
- 1
- 20
- 27
-
how to get absolute path then? – Qaisar Satti May 05 '16 at 11:31
-
let me edit the answer. – R T May 05 '16 at 11:32
-
2It works like a charm !! – Nalin Savaliya Nov 29 '16 at 13:49
7
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
}
}
Key Shang
- 3,415
- 32
- 58