Copied to clipboard

Flag this post as spam?

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


  • Jason D 69 posts 221 karma points
    6 days ago
    Jason D
    0

    Get Media File by Name in Umbraco 13

    Hi there, I've been searching documentation and the web, while trying quite a few ways to simply lookup a media file by a name ("file.pdf"), by using the Umbraco API for the Media Service and/or Media File Manager, and I can't seem to accomplish it by using file name (versus path, GUID, etc).

    I am refactoring older code that used SQL to directly check for the file name in the database, but I want to have it updated.

    Is there no other way to check for existing media file?

    I actually had a pretty elaborate set of methods that would look locally, and then if no, would switch to look in the blob service. But this seemed like stepping outside the context of Umbraco's capabilities.

  • Simon Napper 88 posts 279 karma points
    6 days ago
    Simon Napper
    0

    If you've got access to the published cache, you could try something like this (I'm writing this off the top of my head so might not work!)

    umbracoContext.Media.GetAtRoot().Where(x=>x.Value<string>("umbracoFile").InvariantEquals("file.pdf"));
    

    Something like that?

  • Yakov Lebski 571 posts 2177 karma points
    6 days ago
    Yakov Lebski
    0
    private readonly IMediaService mediaService;       
    mediaService.GetMediaByPath(mediaPath)
    

    will generate direct SQL request to DB

  • Simon Napper 88 posts 279 karma points
    6 days ago
    Simon Napper
    0

    It will if you have the full path (i.e. /media/1024/file.pdf) but not sure it will work with just the file name?

    In an ideal world it's best to avoid hitting the DB via the MediaService if you can access the cache for looking things up, but depends if you want to then update it once you've got it!

  • Yakov Lebski 571 posts 2177 karma points
    6 days ago
    Yakov Lebski
    0

    yep, it will for relative path i.e. /media/1024/file.pdf,

    using publishing api need to also think about folder, for big website can be slow

    for big site examine query will be better solution

  • Jason D 69 posts 221 karma points
    6 days ago
    Jason D
    0

    Thank you guys! You gave me some things to try.

    For context, I don't know the media folder ("media/0csnrul/"), or if my startup.cs is using local or azure media.

    Examine might be the best, however my goal is to get existing media file if exists and replace File, but keep path intact.

Please Sign in or register to post replies

Write your reply to:

Draft