Question

I have a module that has a phtml file. I want to add an image from pub/media in that phtml file, but my attempts have been unsuccessful.

pub / media / catalog / category / shutterstock_259609874 jpg

I tried this, but it is is not working:

https://magento.stackexchange.com/a/133017

Was it helpful?

Solution

In your Block file add:

public function __construct(
        ...
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        ...
    ) {
        $this->storeManager = $storeManager;
    }


    /**
     * @return mixed
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getMediaUrl()
    {
        return $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
    }

And in phtml file write:

<?php echo $block->getMediaUrl() . 'catalog/category/shutterstock_259609874.jpg'; ?>

OTHER TIPS

Try this

<?php

namespace Vendor\Module\Model\Config\Category;

use \RecursiveDirectoryIterator;
use \RecursiveIteratorIterator;

class SavedImages implements \Magento\Framework\Option\ArrayInterface
{
/**
 * @var Data
 */
private $helper;

/**
 * @var File
 */
private $io;


public function __construct(
    \Vendor\Module\Helper\Data $helper,
    \Magento\Framework\Filesystem\Io\File $io
) {
    $this->helper = $helper;
    $this->io     = $io;
}

public function toOptionArray()
{
    $directory = $this->helper->getBaseDir() . '/catalog/category';
    if ($this->io->checkAndCreateFolder($directory)) {
        $savedImages = $this->scanDirectoryItreative($directory);
        return $savedImages;
    } else {
        return [];
    }
}

public function scanDirectoryItreative($path)
{
    $directoryItreator = new RecursiveDirectoryIterator($path);
    $iterator          = new RecursiveIteratorIterator($directoryItreator, RecursiveIteratorIterator::CHILD_FIRST);
    $files             = [];
    foreach ($iterator as $file) {
        $extension         = pathinfo($file, PATHINFO_EXTENSION);
                $splited          = explode("catalog/category", $fullName);
                $temp['name']     = $splited[1];
                $temp['image_id'] = $file->getFileName();
                $files[]          = $temp;
        }
    }
    return $files;
}
}

IN Your Block File

<?php

namespace Vendor\Module\Block;


class SavedImages 
{


public function __construct(
) {
   \Vendor\Module\Model\Config\Category $savedImages
}
   $this->savedImages=$savedImages;
}
 public function getImages() {

   return $this->savedImages->toOptionArray();
}

Now in PHTML file

<?php 
$images=$block->getImages();
?>

<img src="<?php echo $block->getBaseUrl() . 'media/catalog/category/shutterstock_259609874.jpg' ?>">

it's work

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top