Displaying content from media libraries

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.

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

Storage of media files in MVC projects

By default, content of media libraries is synchronized via web farms 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.

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.



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

using CMS.MediaLibrary;
using CMS.SiteProvider;



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):

  • GetDirectUrl – returns a direct URL to the media file on the file system. For example: ~/Kentico/DancingGoat/media/Images/sample_image.jpg

  • GetPermanentUrl – returns a permanent URL to the media file. For example: ~/getmedia/0140bccc-9d47-41ea-94a9-ca5d35b2964c/sample_image.jpg

    The GetPermanentUrl method generates URLs that have the following behavior:

    • Allow checking of media library permissions (see Assigning permissions to media libraries 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.

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

    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:




@{
    // 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.

  2. Always generate URLs for media files by calling the GetPermanentUrl method of the MediaLibraryHelper class.

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

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.