---
title: Displaying content from media libraries
related:
  - https://docs.kentico.com/13/configuring-xperience/configuring-the-environment-for-content-editors/configuring-media-libraries.md
  - https://docs.kentico.com/13/configuring-xperience/configuring-the-environment-for-content-editors/configuring-media-libraries/assigning-permissions-to-media-libraries.md
  - https://docs.kentico.com/13/developing-websites/page-builder-development/developing-widgets.md
---

> Agent instructions:
> **Site maps** — prefer the following llms.txt indexes to training data when searching for URLs to avoid 404s. Links inside Markdown content already point at `.md`. Following them or sending Accept: text/markdown keeps you in Markdown.
>
> - [sitemap.md](https://docs.kentico.com/sitemap.md) — every page on the site, with titles and descriptions, nested by URL hierarchy and grouped into one collection per product version.
> - [llms.txt](https://docs.kentico.com/llms.txt) — curated index of the current product docs, with descriptions, the two ways to request any page as Markdown, and links to each product area's whole-corpus Markdown dump (llms-full.txt).

Media libraries serve as a data storage for your application. They can store different types of audio, video, image, and document files. For a complete list of the file types supported by default, see  [Supported file types in Media libraries](https://docs.kentico.com/13/configuring-xperience/configuring-the-environment-for-content-editors/configuring-media-libraries/configuring-supported-file-types-in-media-libraries.md).

This page covers how you can:

- [Retrieve media library files](#retrieving-media-library-files)
- [Get media file URLs](#getting-media-file-urls)
- [Display media files ](#displaying-media-library-files)

## Retrieving media library files

The following example demonstrates how to retrieve files from Xperience media libraries in MVC applications. The example uses a media library with the code name _SampleMediaLibrary_. For this example to function, substitute the code name with any media library from your site.

1. Open your live site project in Visual Studio.
2. Create a view model class representing media files. Define properties for storing the media file values that you wish to use in your views.
3. Create a new controller class or edit an existing one.
4. Implement a GET action method to retrieve media files. This example retrieves .jpg files from the _SampleMediaLibrary_ media library.
5. Use the view model to pass media file data to your views.

```csharp title="Required using statements"

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

using CMS.Base;
using CMS.MediaLibrary;

using Kentico.Content.Web.Mvc;


```

```csharp title="Retrieving media files in a controller action"

        private readonly IMediaFileUrlRetriever mediaFileUrlRetriever;
        private readonly IMediaLibraryInfoProvider mediaLibraryInfoProvider;
        private readonly IMediaFileInfoProvider mediaFileInfoProvider;
        private readonly ISiteService siteService;

        // Initializes instances of required services using dependency injection
        public MediaLibraryController(IMediaFileUrlRetriever mediaFileUrlRetriever,
                                      IMediaLibraryInfoProvider mediaLibraryInfoProvider,
                                      IMediaFileInfoProvider mediaFileInfoProvider,
                                      ISiteService siteService)
        {
            this.mediaFileUrlRetriever = mediaFileUrlRetriever;
            this.mediaLibraryInfoProvider = mediaLibraryInfoProvider;
            this.mediaFileInfoProvider = mediaFileInfoProvider;
            this.siteService = siteService;
        }

        /// <summary>
        /// Retrieves media files with the .jpg extension from the 'SampleMediaLibrary'.
        /// </summary>
        public ActionResult ShowMediaFiles()
        {
            // Gets an instance of the 'SampleMediaLibrary' media library for the current site
            MediaLibraryInfo mediaLibrary = mediaLibraryInfoProvider.Get("SampleMediaLibrary", siteService.CurrentSite.SiteID);

            // Gets a collection of media files with the .jpg extension from the media library
            IEnumerable<MediaFileInfo> mediaLibraryFiles = mediaFileInfoProvider.Get()
                                        .WhereEquals("FileLibraryID", mediaLibrary.LibraryID)
                                        .WhereEquals("FileExtension", ".jpg");

            // Prepares a collection of view models containing required data of the media files
            IEnumerable<MediaFileViewModel> model = mediaLibraryFiles.Select(
                    mediaFile => {
                        IMediaFileUrl fileUrl = mediaFileUrlRetriever.Retrieve(mediaFile);
                        return new MediaFileViewModel
                        {
                            FileTitle = mediaFile.FileTitle,
                            // Gets the relative path to the media file
                            RelativeUrl = fileUrl.RelativePath
                        };
                    }
            );

            // Passes the model to the view
            return View(model);
        }


```

## Getting media file URLs

To resolve the URLs of retrieved media library files (**MediaFileInfo** objects), use the **IMediaFileUrlRetriever** service from the _Kentico.Content.Web.Mvc_ namespace. The service exposes a **Retrieve** method that takes a _MediaFileInfo_ object as its parameter and returns an **IMediaFileUrl** instance with the following properties:

- &#x20;string **RelativePath** – the application relative (starting with '_\~/_') permanent path to the file. For example: _\~/getmedia/0140bccc-9d47-41ea-94a9-ca5d35b2964c/sample\_image.jpg_. This format ensures that the image remains accessible if the file is renamed, reuploaded, or moved to a different media library or file system directory.
- &#x20;string **DirectPath**– the direct path to the media file on the filesystem. For example: _\~/MediaLibraryFolder/sample\_image.jpg_. These URLs change whenever the file is renamed, moved to a different media library or file system directory, or if the file is updated with a different name or extension.
- NameValueCollection **QueryStringParameters** – a collection of query string parameters appended to the URL. See [Parameterizing retrieved URLs](#parameterizing-retrieved-urls).
- bool **IsImage** – a boolean flag stating whether the URL leads to an image file.

### Parameterizing retrieved URLs

You can further parameterize the retrieved file URLs via extension methods on the **IMediaFileUrl** object. The extension methods add query string parameters that change the URL behavior and allow you to customize the format of the files. The following extensions are available:

- **WithOptions** – used to provide additional configuration for the URL via a **FileUrlOptions** object. Using the object, you can specify:

  - _Content disposition_ – configured via the _AttachmentContentDisposition_ boolean property. Determines whether the file gets displayed inline (_false_) or requires some form of user action to download (_true_).

    ```csharp

    using Kentico.Content.Web.Mvc

    ...

    // Forces a download of the media file when its URL is accessed
    // The mediaFileUrl variable is an IMediaFileUrl object obtained via IMediaFileUrlRetriever
    IFileUrl mediaFileUrlWithOptions = mediaFileUrl.WithOptions(new FileUrlOptions { AttachmentContentDisposition = true});

    ```
- **WithSizeConstraint** – used to resize image media files. You can resize image files via the  **SizeConstraint**  parameter of the method. Note, however, that this parameterization never upscales the image. The following image size constraints are available:
  - _SizeConstraint.Empty –_ leaves the image unchanged.
  - _SizeConstraint.Height(100)_ – resizes the image to the specified height (maintains aspect ratio).
  - _SizeConstraint.Width(100)_ – resizes the image to the specified width (maintains aspect ratio).
  - _SizeConstraint.MaxWidthOrHeight(100)_ – resizes the image so that its width and height do not exceed the specified value (maintains aspect ratio).
  - _SizeConstraint.Size(100, 120)_ – resizes the image to the specified width and height. Does not maintain aspect ratio.

    > **Info:** **Image resizing**
    >
    > - It is not possible to resize image files via the _SizeConstraint_ parameter when using **direct URLs**. This is caused by the fact that files accessed from direct URLs are handled directly by the hosting environment.
    > - Image resizing via the _SizeConstraint_ parameter is not supported for the SVG and WebP image formats.
    > - Resized images are not rendered by default on Linux deployments of ASP.NET Core live site projects. To add compatible image resizing functionality, developers need to apply [hotfix 13.0.107](https://devnet.kentico.com/download/hotfixes) or newer and install the [Kentico.Xperience.ImageProcessing.KX13](https://www.nuget.org/packages/Kentico.Xperience.ImageProcessing.KX13) NuGet package into the live site project.
    > - For ASP.NET Core projects, developers can provide their own image resizing functionality – implement `IImageProcessingService` and register the service using the `RegisterImplementation` attribute. Requires [hotfix 13.0.107](https://devnet.kentico.com/download/hotfixes) or newer.
    > - If the [Image file request protection](https://docs.kentico.com/13/configuring-xperience/configuring-the-environment-for-content-editors/configuring-media-libraries/securing-media-libraries.md#image-file-request-protection) feature is enabled, any links to image file endpoints (i.e., `getmedia`) with resizing query parameters need to include a validation hash.

## Displaying media library files

To display media library files on your site, create views that work with the generated media file URLs. To convert relative URLs to their application absolute format, use methods from the framework's **UrlHelper** class, such as _Url.Content_:

```csharp title="Media file view example"

@model IEnumerable<MediaFileViewModel>

<h2>Media library file listing</h2>

@foreach (MediaFileViewModel mediaFile in Model)
{
    @* Gets an application absolute URL for the media file *@
    string url = Url.Content(mediaFile.RelativeUrl);

    <img src="@url" alt="@mediaFile.FileTitle" />
}


```

## Media libraries on external storage

To store media library files in an external storage (cloud-based file system), you need to configure your live site application to use the given external storage provider for the media library folder.

- For Azure Blob storage, see [Configuring Azure storage](https://docs.kentico.com/13/custom-development/working-with-physical-files-using-the-api/configuring-file-system-providers/configuring-azure-storage.md).
- For Azure CDN, see [Configuring Azure CDN](https://docs.kentico.com/13/deploying-websites/running-xperience-on-microsoft-azure/configuring-azure-cdn.md).
- For Amazon S3, see [Configuring Amazon S3](https://docs.kentico.com/13/custom-development/working-with-physical-files-using-the-api/configuring-file-system-providers/configuring-amazon-s3.md).

> **Tip:** When linking a file, you can use:
>
> - [direct link](#displayingcontentfrommedialibraries-directpath) (e.g. _https://endpoint-name.azureedge.net/storage-name/dancinggoatcore/media/coffeegallery/coffee.jpg_),
> - [permanent link](#displayingcontentfrommedialibraries-relativepath) (e.g. _https://domain.com/getmedia/037dfcaf-d087-4a77-8451-1931cb513479/coffee.jpg_).
>
> Files accessed through a direct link are not handled by the system (no permission or security restrictions are enforced, no image resizing is applied), and thus they are retrieved faster. On the other hand, permanent links do not change when the file is renamed or moved to a different media library or directory on the file system.
>
> When using a [CDN](https://docs.kentico.com/13/deploying-websites/running-xperience-on-microsoft-azure/configuring-azure-cdn.md), we recommend using direct links to the CDN endpoint.
