How to get media url in Magento 2?

by raphael_tillman , in category: PHP CMS , 2 years ago

How to get media url in Magento 2?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by hal.littel , 2 years 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.

Member

by addison , a year ago

@raphael_tillman 

To get the media URL in Magento 2, you can use the MagentoStoreModelStoreManagerInterface and MagentoFrameworkUrlInterface classes. Here is an example of how to retrieve the media URL in a PHP class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
use MagentoStoreModelStoreManagerInterface;
use MagentoFrameworkUrlInterface;

class MyClass
{
    protected $storeManager;
    protected $urlBuilder;
    
    public function __construct(
        StoreManagerInterface $storeManager,
        UrlInterface $urlBuilder
    ) {
        $this->storeManager = $storeManager;
        $this->urlBuilder = $urlBuilder;
    }
    
    public function getMediaUrl($file)
    {
        $mediaUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
        return $mediaUrl . $file;
    }
}


In the example above, you are injecting the StoreManagerInterface and UrlInterface dependencies into your class constructor using dependency injection. Then, you can use the getMediaUrl() method to return the full media URL for a given file.