Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Mahender Singh 39 posts 171 karma points
    Jun 09, 2022 @ 15:19
    Mahender Singh
    0

    How to get Media using MediaService

    Hi Team,

    I want to access all Media that exists in perticular folder. To access i have only folder name not id for any thing..either Images or folder.

    Also I want to access that media(Images) public URL so that i can access that image in browser or html(by assign href in img).

    Please help me in this.

  • Huw Reddick 1929 posts 6697 karma points MVP 2x c-trib
    Jun 10, 2022 @ 09:49
    Huw Reddick
    102

    You will need to inject IMediaTypeService and IMediaService

    Then the following code should give you what you want, I can't say it is the correct or best way, but should work ok :)

        @{
        var folderType = mtype.Get("folder");
    
        var folders = mediaService.GetPagedOfType(folderType.Id, 0, 20, out var total).Where(m => m.Name == NAMEOFYOURFOLDER);
    
        var enumerableFolders = folders as IMedia[] ?? folders.ToArray();
        if (enumerableFolders.Any())
        {
            @foreach (var folder in enumerableFolders)
            {
                var imagesInFolder = mediaService.GetPagedChildren(folder.Id, 0, 50, out var totalimages);
    
                <ul class="list-unstyled">
                    @foreach (var image in imagesInFolder)
                    {
                        dynamic umbracoFile = JsonConvert.DeserializeObject(image.GetValue<string>(Constants.Conventions.Media.File));
    
                    <li>@umbracoFile.src</li>
                    }
                </ul>
            }
        }
    }
    
Please Sign in or register to post replies

Write your reply to:

Draft