Create folders & upload images under Media in Umbraco

This is a continuation from my previous post about downloading and uploading images to media programmatically, via code.

This example code will help you create folders under Media in the following hierarchy –

Video Images

-> 2018 (current year)

-> November (current month)

public class ImageService
{
  private readonly IUmbracoContextWrapper _umbCtxtHelper;
  private readonly IMediaService _mediaService;

  public ImageService(IUmbracoContextWrapper umbCtxtHelper)
  {
     _umbCtxtHelper = umbCtxtHelper;
     _mediaService = _umbCtxtHelper.MediaService;
  }  

  public int UploadMedia(string imageSrc)
  {
   IMedia newImage = null;
   try
   {
     var mediaSvc = _mediaService;
     var mediaExtension = Path.GetExtension(imageSrc);
     var imageName = Guid.NewGuid() + mediaExtension;

     var image = DownloadImageFromUrl(imageSrc);

     const string rootPath = "~\\media";
     var fileName = 
     HttpContext.Current.Server.MapPath(Path.Combine(rootPath, imageName));
     image.Save(fileName);

     // Here we are creating the folders and adding images to them
     var parentFolderId = GetFolderId();
     newImage = mediaSvc.CreateMedia(imageName, parentFolderId, "Image");

     var buffer = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~\\media\\" + imageName));

     newImage.SetValue("umbracoFile", imageName, new MemoryStream(buffer));
     mediaSvc.Save(newImage);

     if (System.IO.File.Exists(HttpContext.Current.Server.MapPath("~\\media\\" + imageName)))
     {
       System.IO.File.Delete(HttpContext.Current.Server.MapPath("~\\media\\" + imageName));
      }
   }
   catch (Exception ex)
   {
     // log the exception
   }
   return newImage.Id;
  }
private System.Drawing.Image DownloadImageFromUrl(string imageUrl)
  {
   System.Drawing.Image image = null;
   try
   {
     var webRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
     webRequest.AllowWriteStreamBuffering = true;
     webRequest.Timeout = 30000;

     var webResponse = webRequest.GetResponse();
     var stream = webResponse.GetResponseStream();
     image = System.Drawing.Image.FromStream(stream);

     webResponse.Close();
   }
   catch (Exception ex)
   {
     // log the exception
   }
   return image;
  }   
private static int GetFolderId()
  {
    var currentYear = DateTime.Now.Year.ToString();
    var currentMonth = DateTime.Now.ToString("MMMM", CultureInfo.InvariantCulture);

    var parentFolder = GetParentFolder("Video Images")
                                  ?? CreateAndSaveMediaFolder("Video Images", -1);

    var yearFolder = GetSubFolder(parentFolder.Id, currentYear)
                                ?? CreateAndSaveMediaFolder(currentYear, genreFolder.Id);

    var monthFolder = GetSubFolder(yearFolder.Id, currentMonth)
                                 ?? CreateAndSaveMediaFolder(currentMonth, yearFolder.Id);

    return monthFolder.Id;
  }
private static IMedia CreateAndSaveMediaFolder(string folderName, int parentFolderId)
  {
    var folder = _mediaService.CreateMedia(folderName, parentFolderId, "Folder");
    _mediaService.Save(folder);
    return folder;
  }
private IMedia GetSubFolder(int parentFolderId, string folderName)
        {           
            var folder = _mediaService.GetChildren(parentFolderId)
                .Where(c => c.ContentType.Name == "Folder" && c.Name.Equals(folderName, StringComparison.OrdinalIgnoreCase))
                .Select(f => f).FirstOrDefault();

            return folder;
        }
private IMedia GetParentFolder(string folderName)
        {          
            var folder = _mediaService.GetRootMedia()
                .Where(m => m.ContentType.Name == "Folder" && m.Name.Equals(folderName, StringComparison.OrdinalIgnoreCase))
                .Select(y => y).FirstOrDefault();

            return folder;
        }
public interface IUmbracoContextWrapper
{
   IMediaService MediaService { get; }
}

Extended Gaming Mouse Pad, VicTsing Large Size Mouse and Keyboard Mat for Gaming and Working – 80x40cm (31.5×15.75in)


Sandisk SDSQXA1-128G-GN6MA Extreme 128GB microSD UHS-I Card Adapter 160MB/s U3 A2, Black

Disclosure: We use affiliate links to monetize our content.  We may receive a commission on products or services that you purchase through clicking on links within this blog.

Upload images to Umbraco

It is easy to upload images to Media folder in Umbraco but there are some instances where you need to upload images to media folder programatically, via code.

Here is the code to do that. You can use this code to download and upload any image.


public class ImageService
{
  private readonly IUmbracoContextWrapper _umbCtxtHelper;
private readonly IMediaService _mediaService;

  public ImageService(IUmbracoContextWrapper umbCtxtHelper)
  {
     _umbCtxtHelper = umbCtxtHelper;
_mediaService = _umbCtxtHelper.MediaService;
  }  

  public int UploadMedia(string imageSrc)
  {
   IMedia newImage = null;
   try
   {
var mediaSvc = _mediaService;
     var mediaExtension = Path.GetExtension(imageSrc);
     var imageName = Guid.NewGuid() + mediaExtension;

     var image = DownloadImageFromUrl(imageSrc);

     const string rootPath = "~\\media";
     var fileName = HttpContext.Current.Server.MapPath(Path.Combine(rootPath, imageName));
     image.Save(fileName);

     // -1 is the root folderID, i.e. Media.
     // All images will be saved under Media in Umbraco
     newImage = mediaSvc.CreateMedia(imageName, -1, "Image");
     var buffer = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath("~\\media\\" + imageName));

     newImage.SetValue("umbracoFile", imageName, new MemoryStream(buffer));
     mediaSvc.Save(newImage);

     if (System.IO.File.Exists(HttpContext.Current.Server.MapPath("~\\media\\" + imageName)))
     {
       System.IO.File.Delete(HttpContext.Current.Server.MapPath("~\\media\\" + imageName));
      }
   }
   catch (Exception ex)
   {
     // log the exception
   }

   return newImage.Id;
  }

  private System.Drawing.Image DownloadImageFromUrl(string imageUrl)
  {
   System.Drawing.Image image = null;
   try
   {
     var webRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
     webRequest.AllowWriteStreamBuffering = true;
     webRequest.Timeout = 30000;

     var webResponse = webRequest.GetResponse();
     var stream = webResponse.GetResponseStream();
     image = System.Drawing.Image.FromStream(stream);

     webResponse.Close();
   }
   catch (Exception ex)
   {
     // log the exception
   }
   return image;
  }
}

public interface IUmbracoContextWrapper
{
   IMediaService MediaService { get; }
}

If you want to create folders under Media and upload images to those in Umbraco. Read this post here