Esempio n. 1
0
        private void UploadContactPicture(Dictionary <string, object> variables)
        {
            if (!variables.ContainsKey("ContactPicture"))
            {
                return;
            }
            var base64 = (string)variables["ContactPicture"];

            if (string.IsNullOrEmpty(base64))
            {
                return;
            }
            var database = Sitecore.Context.ContentDatabase;

            Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions
            {
                Database    = database,
                FileBased   = false,
                Destination = "/sitecore/media library/Images/xgen/" + Math.Abs(base64.GetHashCode()),
            };

            var match = Regex.Match(base64, @"data:(?<type>.+?),(?<data>.+)", RegexOptions.Compiled);

            using (Stream stream = new MemoryStream(Convert.FromBase64String(match.Groups["data"].Value)))
            {
                var item = Sitecore.Resources.Media.MediaManager.Creator.CreateFromStream(stream, "/contacts/", options);
                variables["ContactPicture"] = item.ID;
            }

            // Sitecore.Data.Items.MediaItem mediaItem = new Sitecore.Data.Items.MediaItem(item);
        }
        public MediaItem AddFile(string fileName, string mediaItemName)
        {
            string sitecorePath = "/sitecore/media library/Images/Poses/wordpress";

            // Create the options
            Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions();
            // Store the file in the database, not as a file
            options.FileBased = false;
            // Remove file extension from item name
            options.IncludeExtensionInItemName = false;
            // Overwrite any existing file with the same name
            options.KeepExisting = false;
            // Do not make a versioned template
            options.Versioned = false;
            // set the path
            options.Destination = sitecorePath + "/" + mediaItemName;
            // Set the database
            options.Database = Sitecore.Configuration.Factory.GetDatabase("master");

            // Now create the file
            Sitecore.Resources.Media.MediaCreator creator = new Sitecore.Resources.Media.MediaCreator();
            string    mediaitempath  = sitecorePath + "/" + fileName;
            Item      posesMediaItem = Sitecore.Context.Database.GetItem(mediaitempath);
            MediaItem mediaItem      = null;

            if (posesMediaItem == null)
            {
                mediaItem = creator.CreateFromFile(fileName, options);
            }
            return(mediaItem);
        }
Esempio n. 3
0
 public Item CreateorUpdateMedia(string sitecorePath, string sourcePath, string mediaItemName)
 {
     try
     {
         Database masterDb = Sitecore.Configuration.Factory.GetDatabase("master");
         // ItemUri itemUri = ItemUri.Parse(sitecorePath + "/" + mediaItemName);
         // Item myItem = Database.GetItem(itemUri);
         // Create the options
         Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions();
         // Store the file in the database, not as a file
         options.FileBased = false;
         // Remove file extension from item name
         options.IncludeExtensionInItemName = false;
         // Overwrite any existing file with the same name
         options.OverwriteExisting = true;
         // Do not make a versioned template
         options.Versioned = false;
         // set the path
         options.Destination = sitecorePath;
         options.Destination = options.Destination + "/" + mediaItemName;
         options.Database    = masterDb;
         // Now create the file
         Sitecore.Resources.Media.MediaCreator creator = new Sitecore.Resources.Media.MediaCreator();
         var mediaItem = masterDb.GetItem(sourcePath);
         if (mediaItem != null)
         {
             FileInfo     fi = new System.IO.FileInfo(sourcePath);
             FileStream   fs = fi.OpenRead();
             MemoryStream ms = new MemoryStream();
             ms.SetLength(fs.Length);
             fs.Read(ms.GetBuffer(), 0, (int)fs.Length);
             ms.Flush();
             fs.Close();
             MediaItem updatedItem = creator.AttachStreamToMediaItem(ms, sitecorePath, mediaItemName, options);
             if (updatedItem != null)
             {
                 ms.Dispose();
                 return(updatedItem);
             }
         }
         else
         {
             MediaItem newItem = creator.CreateFromFile(sourcePath, options);
             if (newItem != null)
             {
                 return(newItem);
             }
         }
     }
     catch (Exception ex)
     {
     }
     return(null);
 }
        /// <summary>
        /// Save image in the Media library
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="fileName"></param>
        /// <param name="path"></param>
        /// <param name="mediaItemName"></param>
        /// <returns></returns>
        private bool UploadMediaItem(Stream stream, string fileName, string path, string mediaItemName)
        {
            if (string.IsNullOrWhiteSpace(fileName) || string.IsNullOrWhiteSpace(path) || string.IsNullOrWhiteSpace(mediaItemName))
            {
                Sitecore.Diagnostics.Log.Error($"Could not upload media item either filename, path or mediaitemname is null.", this);
                return(false);
            }

            if (stream == Stream.Null)
            {
                Sitecore.Diagnostics.Log.Error($"Could not upload stream is null for media item {mediaItemName}.", this);
                return(false);
            }

            string destination = $"{path}/{mediaItemName}";

            try
            {
                Sitecore.Resources.Media.MediaCreatorOptions options =
                    new Sitecore.Resources.Media.MediaCreatorOptions()
                {
                    FileBased = false,
                    IncludeExtensionInItemName = false,
                    OverwriteExisting          = true,
                    Versioned     = false,
                    Destination   = destination,
                    Database      = Sitecore.Configuration.Factory.GetDatabase(masterDb),
                    AlternateText = mediaItemName
                };

                using (new SecurityDisabler())
                {
                    Sitecore.Resources.Media.MediaCreator creator = new Sitecore.Resources.Media.MediaCreator();
                    MediaItem mediaItem = creator.CreateFromStream(stream, fileName, options);
                    if (mediaItem != null)
                    {
                        Log.Info($"Media Item {destination} uploaded successfully.", this);
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error($"Error uploading Media Item {destination}", ex, this);
            }
            finally
            {
                stream.Dispose();
            }

            return(false);
        }
Esempio n. 5
0
        public MediaItem CreateMedaiItem(Stream stream, string fileName, string sitecorePath)
        {
            Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions()
            {
                FileBased = false,
                IncludeExtensionInItemName = false,
                OverwriteExisting          = false,
                Versioned   = false,
                Destination = sitecorePath + "/" + Path.GetFileNameWithoutExtension(fileName),
                Database    = Sitecore.Configuration.Factory.GetDatabase("master")
            };

            Sitecore.Resources.Media.MediaCreator creator = new Sitecore.Resources.Media.MediaCreator();
            MediaItem mediaItem = creator.CreateFromStream(stream, fileName, options);

            return(mediaItem);
        }
Esempio n. 6
0
        public static MediaItem AddImage(Stream stream, string sitecorePath, string mediaItemName)
        {
            Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions
            {
                FileBased = false,
                IncludeExtensionInItemName = false,
                KeepExisting  = false,
                Versioned     = false,
                Destination   = sitecorePath + "/" + mediaItemName,
                Database      = Sitecore.Configuration.Factory.GetDatabase("master"),
                AlternateText = mediaItemName
            };

            Item mediaItem = Sitecore.Resources.Media.MediaManager.Creator.AttachStreamToMediaItem(stream, sitecorePath,
                                                                                                   mediaItemName, options);

            return(mediaItem);
        }
Esempio n. 7
0
        public MediaItem AddFile(string fileName, string sitecorePath, string mediaItemName)
        {
            // Create the options
            Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions();
            // Store the file in the database, not as a file
            options.FileBased = false;
            // Remove file extension from item name
            options.IncludeExtensionInItemName = false;
            // Overwrite any existing file with the same name
//            options.KeepExisting = false;
            // Do not make a versioned template
            options.Versioned = false;
            // set the path
            options.Destination = sitecorePath + "/" + mediaItemName;
            // Set the database
            options.Database = Sitecore.Configuration.Factory.GetDatabase("master");

            // Now create the file
            Sitecore.Resources.Media.MediaCreator creator = new Sitecore.Resources.Media.MediaCreator();
            MediaItem mediaItem = creator.CreateFromFile(fileName, options);

            return(mediaItem);
        }
Esempio n. 8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="db"></param>
        /// <param name="importPath"></param>
        /// <param name="contentPath"></param>
        /// <returns></returns>
        public static MediaItem UploadContent(Database db, string importPath, string contentPath)
        {
            MediaItem mediaItem = null;

            Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions();
            options.Database     = db;
            options.Language     = Sitecore.Globalization.Language.Parse(Sitecore.Configuration.Settings.DefaultLanguage);
            options.Versioned    = Sitecore.Configuration.Settings.Media.UploadAsVersionableByDefault;
            options.Destination  = contentPath;
            options.KeepExisting = false; // force replacement

            try
            {
                Sitecore.Resources.Media.MediaCreator creator = new Sitecore.Resources.Media.MediaCreator();
                mediaItem = creator.CreateFromFile(importPath, options);
            }
            catch (Exception ex)
            {
                Log.Error(String.Format("Genworth.SitecoreExt.Utilities.ContentEditorHelper:UploadContent, exception creating media item {0}, skipping file. Exception: {1}", importPath.Substring(importPath.LastIndexOf("/")), ex.ToString()), typeof(ContentEditorHelper));
                SitecoreExt.Utilities.ContentEditorHelper.MoveFile(importPath, Path.Combine(importPath + ".failed"));
            }

            return(mediaItem);
        }
Esempio n. 9
0
        /// <summary>
        /// save image inside media gallery
        /// </summary>
        /// <param name="image">Image</param>
        /// <param name="fileName">File name</param>
        /// <param name="alternateText">Alternate text image</param>
        public static void SaveImage(Bitmap image, string fileName, string alternateText)
        {
            // Create memory stream object
            var memoryStream = new MemoryStream();

            image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            // save image in Media galley
            var options = new Sitecore.Resources.Media.MediaCreatorOptions
            {
                FileBased                  = false,
                OverwriteExisting          = true,
                Versioned                  = true,
                IncludeExtensionInItemName = true,
                Destination                = fileName,
                Database      = Factory.GetDatabase("master"),
                AlternateText = alternateText
            };

            using (new SecurityDisabler())
            {
                var creator = new Sitecore.Resources.Media.MediaCreator();
                creator.CreateFromStream(memoryStream, fileName, options);
            }
        }
        public static Sitecore.Data.Items.MediaItem AddFile(Sitecore.Data.Database database, UploadFileInfo uploadFileInfo, string destination)
        {
            var itemName = ItemUtil.ProposeValidItemName(uploadFileInfo.FileNameWithoutExtension);
            // Create the options
            var options = new Sitecore.Resources.Media.MediaCreatorOptions();

            // Store the file in the database, not as a file
            options.FileBased = false;
            // Remove file extension from item name
            options.IncludeExtensionInItemName = false;
            // Overwrite any existing file with the same name
            options.OverwriteExisting = true;
            // Do not make a versioned template
            options.Versioned = false;
            // set the path
            options.Destination = destination + "/" + itemName;
            // Set the database
            options.Database = database;

            using (var stream = new MemoryStream(uploadFileInfo.Bytes))
            {
                return(Sitecore.Resources.Media.MediaManager.Creator.CreateFromStream(stream, uploadFileInfo.Name, options));
            }
        }
        public MediaItem AddFile(string fileName, string mediaItemName) {
            string sitecorePath = "/sitecore/media library/Images/Poses/wordpress";
            // Create the options
            Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions();
            // Store the file in the database, not as a file
            options.FileBased = false;
            // Remove file extension from item name
            options.IncludeExtensionInItemName = false;
            // Overwrite any existing file with the same name
            options.KeepExisting = false;
            // Do not make a versioned template
            options.Versioned = false;
            // set the path
            options.Destination = sitecorePath + "/" + mediaItemName;
            // Set the database
            options.Database = master;

            // Now create the file
            Sitecore.Resources.Media.MediaCreator creator = new Sitecore.Resources.Media.MediaCreator();
            string mediaitempath = sitecorePath + "/" + fileName;
            Item posesMediaItem = Sitecore.Context.Database.GetItem(mediaitempath);
            MediaItem mediaItem = null;
            if (posesMediaItem == null) {
                mediaItem = creator.CreateFromFile(fileName, options);
            }
            return mediaItem;
        }
        public bool SubmitFormToEloqua(FormSubmitContext formSubmitContext)
        {
            Logger.Info(Invariant($"Form {formSubmitContext.FormId} submitted successfully."), this);
            HttpPostedFileBase file     = null;
            string             fileName = null;

            foreach (IViewModel field in formSubmitContext.Fields)
            {
                if (field is FileUploadViewModel)
                {
                    var fileUpload = field as FileUploadViewModel;
                    if (fileUpload.Files.Count > 0)
                    {
                        file = fileUpload.Files.First();
                    }
                }

                if (field.Name == "fileName")
                {
                    var textField = field as StringInputViewModel;
                    fileName = textField.Value;
                }
            }

            if (file != null && fileName != null)
            {
                using (new Sitecore.SecurityModel.SecurityDisabler())
                {
                    var master = Sitecore.Configuration.Factory.GetDatabase("master");
                    // Create the options
                    Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions();
                    // Store the file in the database, not as a file
                    options.FileBased = false;
                    // Remove file extension from item name
                    options.IncludeExtensionInItemName = false;
                    // Overwrite any existing file with the same name
                    options.OverwriteExisting = true;
                    // Do not make a versioned template
                    options.Versioned = false;
                    // set the path
                    options.Destination = "/sitecore/media library/Items/Uploaded/" + fileName;
                    // Set the database
                    options.Database = master;

                    var mediaItem = Sitecore.Resources.Media.MediaManager.Creator.CreateFromStream(file.InputStream, fileName + "." + file.FileName.Split(Convert.ToChar(".")).Last(), options);

                    Item         parentItem = master.Items[Sitecore.Context.Site.StartPath];
                    TemplateItem template   = master.GetTemplate(new ID("{744445AA-E445-44C4-85D9-88E5EF8C44F3}"));

                    Item marketplaceItem = parentItem.Add(fileName, template);

                    marketplaceItem.Editing.BeginEdit();

                    try
                    {
                        marketplaceItem.Fields["Name"]?.SetValue(fileName, true);
                        var fileField = (FileField)marketplaceItem.Fields["File"];
                        fileField.MediaID = mediaItem.ID;
                        marketplaceItem.Editing.EndEdit();
                    }
                    catch (Exception ex)
                    {
                        marketplaceItem.Editing.CancelEdit();
                    }

                    PublishItem(mediaItem);
                    PublishItem(marketplaceItem);
                }
            }

            return(true);
        }
Esempio n. 13
0
        /// <summary>
        /// This method will upload pdf file to media library
        /// </summary>
        /// <param name="fullPath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private Item CreateMediaItem(string fullPath, string fileName)
        {
            // Create the options
            Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions();
            // Store the file in the database, not as a file
            options.FileBased = false;
            options.Language  = Sitecore.Globalization.Language.Parse(Sitecore.Configuration.Settings.DefaultLanguage);
            // Remove file extension from item name
            options.IncludeExtensionInItemName = false;
            // Overwrite any existing file with the same name
            options.KeepExisting = false;
            // Do not make a versioned template
            options.Versioned = false;
            // Set the database
            options.Database = Sitecore.Configuration.Factory.GetDatabase("master");
            Item mediaItem = null;

            // set the path
            string sitecorePath = Constants.SITECORE_PATH_TO_PDF_UPLOAD;

            Item pdfFolder = MASTERDB.GetItem(sitecorePath);

            if (pdfFolder != null)
            {
                DateTime dt = DateTime.Parse(tbDate.Text);

                Item yearFolder = pdfFolder.GetChildren().FirstOrDefault(i => i.Name == dt.Year.ToString());

                if (yearFolder == null)
                {
                    using (new SecurityDisabler()) {
                        yearFolder = pdfFolder.Add(dt.Year.ToString(), MediaFolderTemplateItem);
                        itemsToPublish.Add(yearFolder);
                    }
                }

                Item monthFolder = null;

                if (yearFolder != null)
                {
                    monthFolder = yearFolder.GetChildren().FirstOrDefault(i => i.Name == dt.Month.ToString());

                    if (monthFolder == null)
                    {
                        using (new SecurityDisabler()) {
                            monthFolder = yearFolder.Add(dt.Month.ToString(), MediaFolderTemplateItem);
                            itemsToPublish.Add(monthFolder);
                        }
                    }
                }

                Item dayFolder = null;

                if (monthFolder != null)
                {
                    dayFolder = monthFolder.GetChildren().FirstOrDefault(i => i.Name == dt.Day.ToString());

                    if (dayFolder == null)
                    {
                        using (new SecurityDisabler()) {
                            dayFolder = monthFolder.Add(dt.Day.ToString(), MediaFolderTemplateItem);
                            itemsToPublish.Add(dayFolder);
                        }
                    }
                }

                if (dayFolder != null)
                {
                    options.Destination = string.Format("{0}/{1}/{2}/{3}/{4}", sitecorePath, yearFolder.Name, monthFolder.Name, dayFolder.Name, fileName.Replace(".pdf", ""));
                }
                else
                {
                    options.Destination = string.Format("{0}/{1}", sitecorePath, fileName.Replace(".pdf", ""));
                }

                using (new Sitecore.SecurityModel.SecurityDisabler()) {
                    mediaItem = Sitecore.Resources.Media.MediaManager.Creator.CreateFromFile(@fullPath, options);
                    itemsToPublish.Add(mediaItem);
                }
            }

            return(mediaItem);
        }
        public string create_media_item()
        {
            CreatedMediaItem output = new CreatedMediaItem();
            List<HttpPostedFile> files = new List<HttpPostedFile>();
            if (req.Files.Count > 0)
            {
                HttpPostedFile media_file = req.Files["media_file"];
                output.fileName = media_file.FileName;

                var stream = media_file.InputStream;
                using (new Sitecore.SecurityModel.SecurityDisabler())
                {
                    //using (new Sitecore.Data.DatabaseCacheDisabler())
                    //{

                        Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions();
                        options.Database = master;
                        string itemName = media_file.FileName.Replace(".", "_").Replace("&", "_and_");
                        output.itemName = itemName;
                        options.Destination = req.Params["destination"] + "/" + itemName;

                        //create the item
                        Sitecore.Data.Items.Item media_item = Sitecore.Resources.Media.MediaManager.Creator.CreateFromStream(stream, media_file.FileName, options);
                        output.ID = media_item.ID.ToString();

                        // change the template
                        //string TemplateID = "{16692733-9A61-45E6-B0D4-4C0C06F8DD3C}";
                        //Sitecore.Data.Items.TemplateItem template = master.GetTemplate(new Sitecore.Data.ID(TemplateID));
                        //media_item.ChangeTemplate(template);

                        // edit the fields
                        media_item.Editing.BeginEdit();
                        media_item.Fields["Title"].Value = req.Params["title"];
                        media_item.Editing.EndEdit();

                    //}
                }
            }
            return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(output);

            /*
            using (new Sitecore.SecurityModel.SecurityDisabler())
            {

                string ParentID = "{C2902D58-D0D2-4B6C-B93E-87208CFC2C89}";
                string TemplateID = "{962B53C4-F93B-4DF9-9821-415C867B8903}";
                Sitecore.Data.Items.TemplateItem template = master.GetTemplate(new Sitecore.Data.ID(TemplateID));
                Sitecore.Data.Items.Item parent = master.GetItem(new Sitecore.Data.ID(ParentID));
                Sitecore.Data.Items.Item newitem = parent.Add("foo", template);
                return newitem.ID.ToString();

            }
            */
        }
        /// <summary>
        /// Add the image to Sitecore
        /// </summary>
        /// <param name="percolatePost"></param>
        /// <returns></returns>
        public MediaItem CreateMedia(PercolatePost percolatePost)
        {
            //Create the options
            Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions();
            options.FileBased = false;
            options.IncludeExtensionInItemName = false;
            options.KeepExisting = false;
            options.Versioned = false;
            options.Destination = PercolateConstants.Paths.MediaPath + percolatePost.Media.Id;
            options.Database = Sitecore.Configuration.Factory.GetDatabase(Settings.PercolateSettings.MasterDBName);

            //read the image from percolate
            var webClient = new WebClient();
            byte[] imageBytes = webClient.DownloadData(percolatePost.Media.Src);
            MemoryStream stream = new MemoryStream();
            stream.Write(imageBytes, 0, imageBytes.Length);

            //create the image
            Sitecore.Resources.Media.MediaCreator creator = new Sitecore.Resources.Media.MediaCreator();
            MediaItem mediaItem = creator.CreateFromStream(stream, string.Format("{0}.{1}", percolatePost.Media.Id, percolatePost.Media.Format), options);
            
            return mediaItem;
        }
        public MediaItem AddFile(Uri url, string fileName, string originalFileName)
        {
            var mediaFilesContainer =
                Factory.GetDatabase("master").GetItem(new ID("{D05418BD-FDF8-4226-865F-E00FEFA7EDA9}"));
            var mediaFolderTemplate =
                Factory.GetDatabase("master").GetItem(new ID("{FE5DD826-48C6-436D-B87A-7C4210C7413B}"));
            using (var client = new WebClient())
            {
                // Remember to insert the appropriate try..catch..finally blocks.
                // I have refrained from using them to compress the example.
                var sitecoreName = Path.GetFileNameWithoutExtension(fileName);
                sitecoreName = ItemUtil.ProposeValidItemName(sitecoreName.ToLower().Trim());
                var firstLetter = sitecoreName.Substring(0, 1);
                var subFolder = mediaFilesContainer.Children.FirstOrDefault(x => x.Name == firstLetter);
                if (subFolder == null)
                    subFolder = mediaFilesContainer.Add(firstLetter, new TemplateID(mediaFolderTemplate.ID));
                var options = new Sitecore.Resources.Media.MediaCreatorOptions
                {
                    FileBased = false,
                    IncludeExtensionInItemName = false,
                    KeepExisting = false,
                    Versioned = false,
                    Destination = subFolder.Paths.FullPath + "/" + sitecoreName,
                    Database = Factory.GetDatabase("master")
                };
                if (Factory.GetDatabase("master").GetItem(options.Destination) != null)
                    return Factory.GetDatabase("master").GetItem(options.Destination);
                var image = client.DownloadData(url);

                using (var ms = new MemoryStream(image))
                {
                    Item mediaItem =
                        Sitecore.Resources.Media.MediaManager.Creator.CreateFromStream(ms, originalFileName,
                            options);
                    return mediaItem;
                }
                
            }

            return null;
        }
Esempio n. 17
0
        public ActionResult UploadImage()
        {
            bool   isSavedSuccessfully = true;
            string fName = "";

            try
            {
                using (new SecurityDisabler())
                {
                    foreach (string fileName in Request.Files)
                    {
                        HttpPostedFileBase file = Request.Files[fileName];
                        //Save file content goes here
                        if (file != null && file.ContentLength > 0)
                        {
                            var tempStream = new MemoryStream();

                            file.InputStream.CopyTo(tempStream);

                            tempStream.Seek(0, SeekOrigin.Begin);

                            fName = file.FileName;

                            var newFileName =
                                Guid.NewGuid()
                                .ToString()
                                .Replace("-", string.Empty)
                                .Replace("{", string.Empty)
                                .Replace("}", string.Empty);

                            var imagesRootId = ID.Parse(Settings.GetSetting("ImagesRoot"));
                            var imagesRoot   = Sitecore.Context.Database.GetItem(imagesRootId);

                            // Create the options
                            Sitecore.Resources.Media.MediaCreatorOptions options =
                                new Sitecore.Resources.Media.MediaCreatorOptions();
                            // Store the file in the database, not as a file
                            options.FileBased = false;
                            // Remove file extension from item name
                            options.IncludeExtensionInItemName = false;
                            // Overwrite any existing file with the same name
                            options.KeepExisting = false;
                            // Do not make a versioned template
                            options.Versioned = false;
                            options.IncludeExtensionInItemName = false;
                            // set the path
                            options.Destination = imagesRoot.Paths.FullPath + "/" + newFileName;
                            // Set the database
                            options.Database = Sitecore.Configuration.Factory.GetDatabase("master");

                            // Now create the file
                            Sitecore.Resources.Media.MediaCreator creator =
                                new Sitecore.Resources.Media.MediaCreator();

                            MediaItem mediaItem = creator.CreateFromStream(tempStream,
                                                                           newFileName + Path.GetExtension(file.FileName), options);

                            PublishManager.PublishItem(mediaItem, new[] { Database.GetDatabase("web"), },
                                                       new[] { Language.Current }, false, false);


                            CorePipeline.Run("detectFaces", new DetectFacesArgs(mediaItem.InnerItem));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                isSavedSuccessfully = false;
            }

            if (isSavedSuccessfully)
            {
                return(Json(new { Message = fName }));
            }

            return(Json(new { Message = "Error in saving file" }));
        }