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.

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