Displaying content from media libraries

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.

This page covers how you can:

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.
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;



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:

  • 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.
  • 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.
  • 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).

      
      
      
        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.

      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 or newer and install the 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 or newer.
      • If the 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:

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.

When linking a file, you can use:

  • direct link (e.g. https://endpoint-name.azureedge.net/storage-name/dancinggoatcore/media/coffeegallery/coffee.jpg),
  • permanent link (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, we recommend using direct links to the CDN endpoint.