Magento 2: cách xóa hình ảnh hoặc tập tin


9

Cách xóa tập tin hoặc hình ảnh trong magento 2. Tôi biết sử dụng unlink('full file path');sẽ xóa tập tin nhưng tôi muốn làm magento 2 cách . điều kiện khi người dùng checkedxóa checkbox.

Câu trả lời:


15

Câu hỏi rất quan trọng như trong kinh nghiệm của tôi, khi gửi tiện ích mở rộng cho thị trường, xác thực đã tạo ra các lỗi liên quan đến việc sử dụng phương pháp đó trực tiếp. Tôi đã nghiên cứu và tìm thấy giải pháp sau đây.

tiêm cái này \Magento\Framework\Filesystem\Driver\File $filevào constructor của bạn

(đảm bảo khai báo biến cấp lớp tức là, protected $_file;)

và sau đó bạn có thể có quyền truy cập vào các phương thức bao gồm: isExistsdeleteFile

ví dụ: trong constructor

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

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

và sau đó trong phương thức mà bạn đang cố xóa một tệp:

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

hi vọng điêu nay co ich.


Làm thế nào để có được con đường tuyệt đối sau đó?
Qaisar Satti

Hãy để tôi chỉnh sửa câu trả lời.
RT

2
Nó hoạt động như một say mê !!
Nalin Savaliya

6

Câu trả lời của RT là tốt, nhưng chúng ta không nên sử dụng ObjectManager trực tiếp trong ví dụ.

Lý do là ở đây " Magento 2: sử dụng hay không sử dụng ObjectManager trực tiếp ".

Vì vậy, ví dụ tốt hơn là dưới đây:

<?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
    }
}
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.