Copied to clipboard

Flag this post as spam?

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


  • Jason Espin 368 posts 1335 karma points
    May 21, 2014 @ 14:34
    Jason Espin
    0

    Add media item to multiple media picker programatically

    Hi all,

    I am currently creating media items using the following code:

    string originalPath = "uploadedImages\\test.png";
    IMediaService mediaService = ApplicationContext.Current.Services.MediaService;
    var newImage = mediaService.CreateMedia("myTestImage", -1, "Image");
    
    byte[] buffer = System.IO.File.ReadAllBytes(System.IO.Path.GetFullPath(HttpContext.Current.Server.MapPath(originalPath)));
    
    System.IO.MemoryStream strm = new MemoryStream(buffer);
    newImage.SetValue("umbracoFile", "myNewImage.png", strm);
    mediaService.Save(newImage);
    
    if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(originalPath)))
    {
       System.IO.File.Delete(HttpContext.Current.Server.MapPath(originalPath));
    }
    

    My question is, how do I then go about adding these items to a multiple media picker programmatically? Does it just require a string of ids to be passed into one of the properties or does it require an actual image object to be passed in?

  • Bendik Engebretsen 105 posts 202 karma points
    Nov 08, 2016 @ 18:21
    Bendik Engebretsen
    0

    I'm facing the same challenge, did you find out how to do it eventually?

  • Casper 70 posts 308 karma points
    Nov 08, 2016 @ 19:32
    Casper
    2

    I have done it like this:

    int contentId = ...;
    List<int> uploadedMediaIds ...;
    
    if (!contentId.Equals(default(int)))
    {
        var cs = UmbracoContext.Current.Application.Services.ContentService;
        var content = cs.GetById(contentId);
        if (!content.Equals(null))
        {
            var oldValue = content.GetValue<string>(prop);
            var newValue = oldValue + "," + string.Join(",", uploadedMediaIds.Select(i => i.ToString())).Trim(new char[] { ' ', ','});                                             
            content.SetValue(prop, newValue);
            cs.SaveAndPublishWithStatus(content);
        }
    }
    
Please Sign in or register to post replies

Write your reply to:

Draft