How to get media url in Magento 2?

by raphael_tillman , in category: PHP CMS , 8 months ago

How to get media url in Magento 2?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , 3 months ago

@raphael_tillman 

To get the media URL in Magento 2, you can use the following steps:

  1. Create a MagentoFrameworkViewAssetRepository object in your class constructor:
1
2
3
4
5
6
7
protected $assetRepo;

public function __construct(
    MagentoFrameworkViewAssetRepository $assetRepo
) {
    $this->assetRepo = $assetRepo;
}


  1. Use the getUrl() method of the $assetRepo object to get the media URL:
1
$mediaUrl = $this->assetRepo->getUrl('path/to/your/image.jpg');


Note: Replace path/to/your/image.jpg with the actual path to your image file. The path should be relative to the pub/media directory.


Alternatively, you can use the following code to get the media URL:

1
2
3
4
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$storeManager = $objectManager->get('MagentoStoreModelStoreManagerInterface');
$currentStore = $storeManager->getStore();
$mediaUrl = $currentStore->getBaseUrl(MagentoFrameworkUrlInterface::URL_TYPE_MEDIA);


This will give you the base URL for the media directory, which you can then use to construct the full URL for your image file.


For example:

1
$imageUrl = $mediaUrl . 'path/to/your/image.jpg';


I hope this helps! Let me know if you have any questions.