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; }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.