9

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.

15

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.

  • how to get absolute path then? – Qaisar Satti May 5 '16 at 11:31
  • let me edit the answer. – R T May 5 '16 at 11:32
  • 2
    It works like a charm !! – Nalin Savaliya Nov 29 '16 at 13:49
6

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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