---
title: Displaying content from media libraries
related:
  - https://docs.kentico.com/k12sp/managing-website-content/working-with-files/media-library-files.md
  - https://docs.kentico.com/k12sp/configuring-kentico/configuring-the-environment-for-content-editors/configuring-media-libraries.md
  - https://docs.kentico.com/k12sp/configuring-kentico/configuring-the-environment-for-content-editors/configuring-media-libraries/assigning-permissions-to-media-libraries.md
  - https://docs.kentico.com/k12sp/deploying-websites/running-kentico-on-microsoft-azure/configuring-azure-cdn.md
  - https://docs.kentico.com/k12sp/custom-development/working-with-physical-files-using-the-api/configuring-file-system-providers/configuring-amazon-s3.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 represent a data storage for your MVC 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/k12sp/configuring-kentico/configuring-the-environment-for-content-editors/configuring-media-libraries/configuring-supported-file-types-in-media-libraries.md).

You can retrieve media library files in MVC applications by using the Kentico API methods from the **CMS.MediaLibrary** namespace.

> **Note:** **Storage of media files in MVC projects**
>
> By default, content of media libraries is synchronized via [web farms](https://docs.kentico.com/k12sp/configuring-kentico/setting-up-web-farms.md) and duplicated in the project directories of both the Kentico and MVC application. To store media files in a single location, use the approach described in [Configuring custom storage for media libraries](https://docs.kentico.com/k12sp/configuring-kentico/configuring-the-environment-for-content-editors/configuring-media-libraries.md#configuring-custom-storage-for-media-libraries).

## Retrieving media library files

The following example demonstrates how to retrieve files from Kentico media libraries in MVC applications. The example requires a media library with the code name _SampleMediaLibrary_ to work properly.

1. Open your MVC 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. The following example retrieves .jpg files from the _SampleMediaLibrary_ media library.
5. Use the view model to pass media file data to your views.

```csharp

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

using CMS.MediaLibrary;
using CMS.SiteProvider;


```

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

        /// <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.GetMediaLibraryInfo("SampleMediaLibrary", SiteContext.CurrentSiteName);

            // Gets a collection of media files with the .jpg extension from the media library
            IEnumerable<MediaFileInfo> mediaLibraryFiles = MediaFileInfoProvider.GetMediaFiles()
                .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 => new MediaFileViewModel
                    {
                        FileTitle = mediaFile.FileTitle,
                        DirectUrl = MediaLibraryHelper.GetDirectUrl(mediaFile),
                        PermanentUrl = MediaLibraryHelper.GetPermanentUrl(mediaFile)
                    }
            );

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


```

## Getting media library file URLs

To generate media file URLs for **MediaFileInfo** objects, call the following methods of the **MediaLibraryHelper** class (available in the _CMS.MediaLibrary_ namespace):

- **&#x20;GetDirectUrl** – returns a direct URL to the media file on the file system. For example: _\~/Kentico/DancingGoat/media/Images/sample\_image.jpg_
- **&#x20;GetPermanentUrl** – returns a permanent URL to the media file. For example: _\~/getmedia/0140bccc-9d47-41ea-94a9-ca5d35b2964c/sample\_image.jpg_

  > **Info:** The **GetPermanentUrl** method generates URLs that have the following behavior:
  >
  > - Allow checking of media library permissions (see [Assigning permissions to media libraries](https://docs.kentico.com/k12sp/configuring-kentico/configuring-the-environment-for-content-editors/configuring-media-libraries/assigning-permissions-to-media-libraries.md) for more details)
  > - Allow resizing based on constraints when calling the **ImageUrl** method in views.
  > - Include a URL extension based on the site's **Settings -> URLs and SEO -> Files friendly URL extension** setting (set an empty value for extensionless URLs)

The methods return relative URLs – you need to process the value using the _ImageUrl_ or _FileUrl_ extension method in your views to get the final media file URL for your website.

## Displaying media library files

To display media library files on your MVC site, create views that work with the generated media file URLs. Get the final URLs by calling the **ImageUrl** or **FileUrl** extension methods available in the **Kentico.Content.Web.Mvc** namespace.

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

@model IEnumerable<MediaFileViewModel>

@using Kentico.Content.Web.Mvc
@using Kentico.Web.Mvc

<h2>Media library file listing</h2>

@foreach (MediaFileViewModel mediaFile in Model)
{
    @* Gets a permanent URL for the media file and limits the file's maximum side size to 400 px *@
    string url = Url.Kentico().ImageUrl(mediaFile.PermanentUrl, SizeConstraint.MaxWidthOrHeight(400));

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


```

When using **permanent URLs**, you can resize image files via the **SizeConstraint** parameter of the _ImageUrl_ method. The following image size constraints are available:

- _SizeConstraint.Empty –_ leaves the image as-is
- _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, and does not maintain aspect ratio

  > **Info:** **Notes**:
  >
  > - The resized images are never larger than the original size.
  > - 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 IIS.

The **FileUrl** method allows you to force a file download:

```csharp

@{
    // Generates a URL for the media file that forces download
    Url.Kentico().FileUrl(mediaFile.PermanentUrl, new FileUrlOptions() { AttachmentContentDisposition = true });
}


```

## Media libraries in an external storage

To store media library files in an external storage (cloud-based file system), you need to:

1. Configure your MVC application to use the given external storage provider for the media library folder. The instructions for configuring MVC applications are the same as for Kentico projects.

   - For Azure Blob storage, see [Configuring Azure storage](https://docs.kentico.com/k12sp/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/k12sp/deploying-websites/running-kentico-on-microsoft-azure/configuring-azure-cdn.md).
   - For Amazon S3, see [Configuring Amazon S3](https://docs.kentico.com/k12sp/custom-development/working-with-physical-files-using-the-api/configuring-file-system-providers/configuring-amazon-s3.md).
2. Always generate URLs for media files by calling the **GetPermanentUrl** method of the _MediaLibraryHelper_ class.

> **Note:** **Note**: URLs generated by the _GetDirectUrl_ method for external storage files do not work on MVC applications.

> **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/k12sp/deploying-websites/running-kentico-on-microsoft-azure/configuring-azure-cdn.md), we recommend using direct links to the CDN endpoint.
