Magento 2 get media path
Today we discuss about Magento 2 get media path .This tutorial include how to get media path in your block or phtml file. There are two ways to do it. One is factory method and other is use object manager. So let start with our example.
Factory Method
In this example we will get media path. First your need to inject \Magento\Store\Model\StoreManagerInterface.
<?php
/**
* Simple Hello World Module
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email qaisarssatti@gmail.com
*
*/
namespace QaisarSatti\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $storeManager;
public function __construct(
\Magento\Store\Model\StoreManagerInterface $storeManager,
) {
$this->storeManager = $storeManager;
}
public function getMediaUrl()
{
return $mediaUrl = $this->storeManager
->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
}
}
/**
* Simple Hello World Module
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email qaisarssatti@gmail.com
*
*/
namespace QaisarSatti\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $storeManager;
public function __construct(
\Magento\Store\Model\StoreManagerInterface $storeManager,
) {
$this->storeManager = $storeManager;
}
public function getMediaUrl()
{
return $mediaUrl = $this->storeManager
->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
}
}
Object Manager
In this example we will get media path. Using object manager is not recommended.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
echo $objectManager->get('Magento\Store\Model\StoreManagerInterface')
->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
echo $objectManager->get('Magento\Store\Model\StoreManagerInterface')
->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);