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.

2 Answers 2


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;

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.

  • how to get absolute path then? Commented May 5, 2016 at 11:31
  • let me edit the answer.
    – R T
    Commented May 5, 2016 at 11:32
  • 2
    It works like a charm !! Commented Nov 29, 2016 at 13:49

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:

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
        $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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.