Copied to clipboard

Flag this post as spam?

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


  • Darren Eccles 59 posts 298 karma points
    May 07, 2017 @ 21:54
    Darren Eccles
    0

    mediaservice - how do I update an existing file programmatically

    Hi Guys,

    I feel like I've been banging my head against a wall,

    I can quite happily create and save the file using the MediaService with the code below:

    var ms = ApplicationContext.Current.Services.MediaService;
                                IMedia mimage = ms.CreateMedia(model.attachment.FileName, -1, "Image");
                                mimage.SetValue(Constants.Conventions.Media.File, model.attachment);
                                ms.Save(mimage);
    

    When I run the code above I will have a file with the following path '/media/1234/image.jpg' for example.

    I want to be able to update this keeping the same file directory e.g. '/media/1234/updatedimage.jpg' using the mediaservice, is this possible? or do I need to use System.IO?

    Thanks

    Darren

  • Alex Skrypnyk 6150 posts 24110 karma points MVP 8x admin c-trib
    May 07, 2017 @ 22:12
    Alex Skrypnyk
    0

    Hi Darren

    You can do it with .SetValue(string propertyTypeAlias, object value) method. It is possible to pass a HttpPostedFile, HttpPostedFileBase or HttpPostedFileWrapper to the SetValue method, so it can be used for uploads

    https://our.umbraco.org/documentation/Reference/Management/Models/Media#setvalue-string-propertytypealias-object-value

    Thanks,

    Alex

  • Darren Eccles 59 posts 298 karma points
    May 08, 2017 @ 08:06
    Darren Eccles
    0

    Hi Alex,

    Thanks for your reply.

    If I run the same code above for an update, it creates a new folder with the file in, this is because it is using '.CreateMedia()'.

    For example:

    • Run code first time gives me the following folder structure: '/media/1001/image.jpg'
    • Run code second time gives me the following folder structure: '/media/1002/newimage.jpg'

    I want to update the file, keeping the original folder '/media/1001/newimage.jpg'

    I even tried the following:

    var ms = ApplicationContext.Current.Services.MediaService;
    IMedia mimage = ms.GetMediaByPath(original-image);
    mimage.SetValue(Constants.Conventions.Media.File, new-file);
    ms.Save(mimage);
    

    This doesn't work either, to be honest '.GetMediaByPath' finds the file first time, then returns null afterwards. I think there is a bug with this method.

    I'm trying to replicate the file upload function from the back-end on the front-end.

    Thanks again,

    Darren

Please Sign in or register to post replies

Write your reply to:

Draft