Magento 2:如何删除图像或文件


Answers:


15

就我的经验而言,这是一个非常重要的问题,当提交市场扩展时,验证直接产生了与使用这种方法有关的错误。我研究并找到以下解决方案。

将此注入\Magento\Framework\Filesystem\Driver\File $file您的构造函数中

(确保声明类级变量,即protected $_file;

然后你就可以有机会获得包括方法:isExistsdeleteFile

例如:在构造函数中

public function __construct(\Magento\Backend\App\Action\Context $context, 
            \Magento\Framework\Filesystem\Driver\File $file){

        $this->_file = $file;
        parent::__construct($context);
}

然后在您要删除文件的方法中:

$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);
}

希望这可以帮助。


那么如何获得绝对路径呢?
卡萨尔·萨蒂

让我编辑答案。
RT

2
它像一个魅力!
纳林·萨瓦利亚

6

RT的答案很好,但是我们不应在示例中直接使用ObjectManager

原因是“ Magento 2:直接使用或不使用ObjectManager ”。

所以更好的例子如下:

<?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
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.