private void UploadToS3(List <S3MediaUploadResult> list) { Assert.ArgumentNotNull(list, "list"); var upload = new S3MediaUploadResult(); list.Add(upload); upload.Path = FileUtil.MakePath(this.Folder, Path.GetFileName(this.File.FileName), '/'); upload.ValidMediaPath = MediaPathManager.ProposeValidMediaPath(upload.Path); MediaCreatorOptions options = new MediaCreatorOptions { Versioned = this.Versioned, Language = this.Language, KeepExisting = !this.Overwrite, Destination = upload.ValidMediaPath, FileBased = this.FileBased, AlternateText = this.AlternateText, Database = this.Database }; options.Build(GetMediaCreatorOptionsArgs.UploadContext); var item = MediaManager.Creator.CreateFromStream(new MemoryStream(), upload.Path, options); upload.Item = item; S3Client.SendImageToS3(item.ID.ToString(), File.InputStream); }
/// <summary> /// Attach new image to media item /// </summary> /// <param name="imageItem"></param> /// <param name="filename"></param> /// <param name="imageBytes"></param> /// <param name="altText"></param> /// <param name="destPath"></param> /// <param name="errorMessage"></param> private static void AttachNewImageToMediaItem(MediaItem imageItem, string filename, byte[] imageBytes, string altText, string destPath, ref LevelLogger logger) { try { destPath = destPath + "/" + filename; if (imageBytes != null) { using (var ms = new MemoryStream(imageBytes)) { var options = new MediaCreatorOptions { FileBased = false, IncludeExtensionInItemName = false, KeepExisting = false, Versioned = false, AlternateText = altText, Destination = destPath, Database = Database }; MediaManager.Creator.AttachStreamToMediaItem(ms, destPath, filename, options); } } } catch (Exception ex) { logger.AddError(ExceptionTryingToAttachNewImageToExistingMediaitem, String.Format("Error trying to attach new image to existing mediaitem: InnerException {0}. Message {1}", ex.InnerException, ex.Message)); } }
private void CreateNewMediaItemWithStreamAndLink(Stream stream, MediaItem currentItem, LinkField relatedField, Media originalMedia) { var mediaCreator = new MediaCreator(); var options = new MediaCreatorOptions { Versioned = false, IncludeExtensionInItemName = false, Database = Factory.GetDatabase(ImageCompressionConstants.GlobalSettings.Database.Master), Destination = $"/sitecore/media library{currentItem.MediaPath}webp" }; using (new SecurityModel.SecurityDisabler()) { var newHiddenMedia = mediaCreator.CreateFromStream(stream, currentItem.Name + ".webp", options); newHiddenMedia.Editing.BeginEdit(); newHiddenMedia.Appearance.Hidden = true; newHiddenMedia.Editing.EndEdit(); currentItem.BeginEdit(); relatedField.Value = string.Empty; //https://sitecore.stackexchange.com/questions/4104/how-to-programatically-update-a-general-link-field-in-a-custom-user-profille new LinkField(originalMedia.MediaData.MediaItem.InnerItem.Fields[ImageCompressionConstants.ImageFields.RELATED_IMAGE_FIELD]) { LinkType = "internal", TargetID = newHiddenMedia.ID }; currentItem.EndEdit(); } }
public JsonResult Upload(string database = "master", string mediaFolderPath = "/sitecore/media library/Uploaded Files") { SitecoreViewModelResult result = new SitecoreViewModelResult(); try { Database db = Factory.GetDatabase(database); if (db == null) return result; foreach (string file in Request.Files) { HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase; if (hpf.ContentLength == 0 || !ValidateFile(hpf, result)) continue; string fileName = ItemUtil.ProposeValidItemName(Path.GetFileName(hpf.FileName)); MediaCreatorOptions md = new MediaCreatorOptions(); md.Destination = StringUtil.EnsurePostfix('/', StringUtil.EnsurePrefix('/', mediaFolderPath)) + fileName; md.Database = db; using (new SecurityDisabler()) { Item mediaItem = MediaManager.Creator.CreateFromStream(hpf.InputStream, fileName, md); } } } catch (Exception ex) { Log.Error("could not upload", ex, this); } return result; }
private void UpdateMediaItem(ItemModel itemModel) { var bytes = (byte[])Convert.FromBase64String((string)itemModel["Blob"]); using (var stream = GenerateStreamFromByteArray(bytes)) { var creator = new MediaCreator(); var itemId = itemModel[ItemModel.ItemID]; var options = new MediaCreatorOptions(); options.FileBased = false; options.IncludeExtensionInItemName = false; options.OverwriteExisting = true; options.Versioned = false; var mediaItem = Sitecore.Configuration.Factory.GetDatabase("master").GetItem(ID.Parse(itemId)); if (mediaItem != null) { mediaItem.Editing.BeginEdit(); if (mediaItem.Fields["Blob"] != null) { mediaItem.Fields["Blob"].SetBlobStream(stream); } mediaItem.Editing.EndEdit(); } } }
public MediaItem UploadImageFile(string filePath, string newItemPath, string db) { FileStream file = new FileStream(filePath, FileMode.Open); MediaItem mediaItem; using (MemoryStream stream2 = new MemoryStream()) { file.CopyTo(stream2); // Create the options MediaCreatorOptions options = new MediaCreatorOptions { FileBased = false, IncludeExtensionInItemName = false, OverwriteExisting = true, Versioned = false, Destination = newItemPath, Database = Sitecore.Configuration.Factory.GetDatabase(db) }; stream2.Flush(); // upload to sitecore MediaCreator creator = new MediaCreator(); mediaItem = creator.CreateFromStream(stream2, filePath, options); } return(mediaItem); }
protected virtual Item CreateMedia(string rootPath, File mediaFile, string extension, Stream mediaStream) { using (new SecurityDisabler()) { var validItemName = ItemUtil.ProposeValidItemName(mediaFile.FileName); var filesFolder = GetItemByPath(rootPath); if (filesFolder != null) { var files = filesFolder.Children; var item = files.FirstOrDefault(f => f.Name == validItemName && DateUtil.IsoDateToDateTime(f.Fields["__Created"].Value) >= mediaFile.UpdatedDate); if (item != null) { return(item); } } var mediaOptions = new MediaCreatorOptions { Database = ContextDatabase, FileBased = false, IncludeExtensionInItemName = false, KeepExisting = true, Versioned = false, Destination = string.Concat(rootPath, "/", validItemName) }; var previewImgItem = MediaManager.Creator.CreateFromStream(mediaStream, validItemName + "." + extension, mediaOptions); return(previewImgItem); } }
protected MediaCreatorOptions GetDefaultMediaCreatorOptions(string mediaLibraryPath, string itemName) { //Set up the options for creating the new media library options MediaCreatorOptions mediaCreatorOptions; Database masterDb = _sitecoreMasterService.Database; try { //Create the full media library item path including the path and the media item name //itemName = Sitecore.Data.Items.ItemUtil.ProposeValidItemName(itemName); itemName = Regex.Replace(itemName, @"<(.|\n)*?>", string.Empty).Trim(); string fullMediaPath = mediaLibraryPath + @"/" + itemName; mediaCreatorOptions = new MediaCreatorOptions { Destination = fullMediaPath, Database = masterDb, Versioned = true }; } catch (Exception exc) { throw new Exception($"Error creating media creator options when trying to create publication media library item: {exc.Message}"); } return(mediaCreatorOptions); }
public string Execute([NotNull] string databaseName, [NotNull] string newItemPath, [NotNull] string fileStream) { Assert.ArgumentNotNull(databaseName, nameof(databaseName)); Assert.ArgumentNotNull(newItemPath, nameof(newItemPath)); Assert.ArgumentNotNull(fileStream, nameof(fileStream)); var database = Factory.GetDatabase(databaseName); if (database == null) { throw new Exception("Database not found"); } var parentPath = newItemPath; var n = parentPath.LastIndexOf('/'); if (n > 0) { parentPath = parentPath.Left(n); } var parent = database.GetItem(parentPath); if (parent == null) { throw new Exception("Item not found: " + parentPath); } var stream = new MemoryStream(System.Convert.FromBase64String(fileStream)); var options = new MediaCreatorOptions { AlternateText = Path.GetFileNameWithoutExtension(newItemPath), Database = database, FileBased = false, IncludeExtensionInItemName = false, Language = LanguageManager.DefaultLanguage, Versioned = false }; var item = MediaManager.Creator.CreateFromStream(stream, "/upload/" + Path.GetFileName(newItemPath), options); if (item == null) { throw new Exception("Failed to upload file"); } item.MoveTo(parent); var writer = new StringWriter(); var output = new XmlTextWriter(writer); output.WriteStartElement("upload"); output.WriteItemHeader(item); output.WriteEndElement(); return(writer.ToString()); }
private static void ProcessMediaUpload(Stream content, Database db, string itemParam, string entryName, bool skipExisting = false) { var mediaItem = (MediaItem)db.GetItem(itemParam) ?? db.GetItem(itemParam.TrimStart('/', '\\')) ?? db.GetItem(ApplicationSettings.MediaLibraryPath + itemParam); if (mediaItem == null) { var filename = itemParam.TrimEnd('/', '\\').Replace('\\', '/'); var dirName = (Path.GetDirectoryName(filename) ?? string.Empty).Replace('\\', '/'); if (!dirName.StartsWith(Constants.MediaLibraryPath)) { dirName = Constants.MediaLibraryPath + (dirName.StartsWith("/") ? dirName : "/" + dirName); } if (!String.IsNullOrEmpty(entryName)) { dirName += "/" + Path.GetDirectoryName(entryName).Replace('\\', '/'); filename = Path.GetFileName(entryName); } var mco = new MediaCreatorOptions { Database = db, Versioned = Settings.Media.UploadAsVersionableByDefault, Destination = $"{dirName}/{Path.GetFileNameWithoutExtension(filename)}", }; var mc = new MediaCreator(); using (var ms = new MemoryStream()) { content.CopyTo(ms); mc.CreateFromStream(ms, Path.GetFileName(filename), mco); } } else { if (skipExisting) { return; } var mediaUri = MediaUri.Parse(mediaItem); var media = MediaManager.GetMedia(mediaUri); using (var ms = new MemoryStream()) { content.CopyTo(ms); using (new EditContext(mediaItem, SecurityCheck.Disable)) { using (var mediaStream = new MediaStream(ms, media.Extension, mediaItem)) { media.SetStream(mediaStream); } } } } }
public XmlRpcStruct newMediaObject(string blogid, string username, string password, XmlRpcStruct rpcstruct) { // Check user validation Authenticate(username, password); var name = rpcstruct["name"].ToString(); var media = (byte[])rpcstruct["bits"]; var blogName = string.Empty; var currentBlog = GetContentDatabase().GetItem(blogid); blogName = currentBlog.Name; // Get filename var fileName = Path.GetFileName(name); var imageName = ItemUtil.ProposeValidItemName(Path.GetFileNameWithoutExtension(fileName)); // Create strem from byte array var memStream = new MemoryStream(media); var md = new MediaCreatorOptions(); md.Destination = string.Join("/", new string[] { Constants.Paths.WeBlogMedia, blogName, imageName }); md.Database = GetContentDatabase(); md.AlternateText = imageName; // Check access rights CheckUserCreateRights(md.Destination); // Create mediaitem var mediaItem = MediaManager.Creator.CreateFromStream(memStream, fileName, md); // Close stream memStream.Close(); memStream.Dispose(); // Publish mediaitem to web database ContentHelper.PublishItemAndRequiredAncestors(mediaItem.ID); // Get the mediaitem url and return it var rstruct = new XmlRpcStruct(); #if FEATURE_URL_BUILDERS var options = new MediaUrlBuilderOptions() #else var options = new MediaUrlOptions() #endif { AbsolutePath = false, UseItemPath = false }; rstruct.Add("url", MediaManager.GetMediaUrl(mediaItem, options)); return(rstruct); }
private MediaItem Upload([NotNull] Item item, [NotNull] string fieldId, [NotNull] string filename) { Debug.ArgumentNotNull(filename, nameof(filename)); MediaItem mediaItem = null; using (new SecurityDisabler()) { ThumbnailField field = item.Fields[fieldId]; if (field != null) { mediaItem = field.MediaItem; } if (mediaItem == null) { var path = GenerateMediaFolderPath(item.ID); var options = new MediaCreatorOptions { Database = Client.ContentDatabase, Destination = path, KeepExisting = false, Versioned = false, AlternateText = "Thumbnail for " + item.Paths.Path }; var notificationContext = Context.Notifications; if (notificationContext != null) { notificationContext.Disabled = true; } mediaItem = MediaManager.Creator.CreateFromFile(filename, options); if (notificationContext != null) { notificationContext.Disabled = false; } } else { using (var fileStream = new FileStream(FileUtil.MapPath(filename), FileMode.Open, FileAccess.Read, FileShare.Read)) { var media = MediaManager.GetMedia(mediaItem); media.SetStream(fileStream, "png"); } } return(mediaItem); } }
public JsonResult Upload(string database, string destinationUrl) { List <UploadedFileItem> list = new List <UploadedFileItem>(); SitecoreViewModelResult result = new SitecoreViewModelResult(); foreach (string str in base.Request.Files) { HttpPostedFileBase file = base.Request.Files[str]; if (file != null) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file.FileName); fileNameWithoutExtension = ItemUtil.ProposeValidItemName(fileNameWithoutExtension, "default"); Database contentDatabase = Context.ContentDatabase; if (!string.IsNullOrEmpty(database)) { contentDatabase = Factory.GetDatabase(database); } if (contentDatabase == null) { contentDatabase = Context.ContentDatabase; } MediaCreatorOptions options = new MediaCreatorOptions { Database = contentDatabase, FileBased = false, IncludeExtensionInItemName = Settings.Media.IncludeExtensionsInItemNames, KeepExisting = true, Language = LanguageManager.DefaultLanguage, Versioned = false, Destination = this.ParseDestinationUrl(destinationUrl) + fileNameWithoutExtension }; if (!ValidateFile(file, result)) { return(result); } Item innerItem = MediaManager.Creator.CreateFromStream(file.InputStream, "/upload/" + file.FileName, options); MediaItem item = new MediaItem(innerItem); string mediaUrl = MediaManager.GetMediaUrl(item); list.Add(new UploadedFileItem(innerItem.Name, innerItem.ID.ToString(), innerItem.ID.ToShortID().ToString(), mediaUrl)); } } ((dynamic)result.Result).uploadedFileItems = list; return(result); }
/// <summary> /// Imports an image into the root of the Sitecore media library /// </summary> /// <param name="sampleImage"></param> public static void ImportImage(string sampleImage) { FileInfo imageFile = new FileInfo(sampleImage); Item parentItem = Sitecore.Context.Database.GetItem("/sitecore/media library"); var mediaCreatorOptions = new MediaCreatorOptions(); mediaCreatorOptions.Database = Sitecore.Context.Database; mediaCreatorOptions.Language = Sitecore.Context.Language; mediaCreatorOptions.Versioned = false; mediaCreatorOptions.Destination = string.Format("{0}/{1}", parentItem.Paths.FullPath, ItemUtil.ProposeValidItemName(Path.GetFileNameWithoutExtension(sampleImage))); mediaCreatorOptions.FileBased = Sitecore.Configuration.Settings.Media.UploadAsFiles; var mc = new MediaCreator(); mc.CreateFromFile(sampleImage, mediaCreatorOptions); }
/// <summary> /// Imports an image into the root of the Sitecore media library /// </summary> /// <param name="sampleImage"></param> public static void ImportImage(string sampleImage) { FileInfo imageFile = new FileInfo(sampleImage); Item parentItem = Sitecore.Context.Database.GetItem("/sitecore/media library"); var mediaCreatorOptions = new MediaCreatorOptions(); mediaCreatorOptions.Database = Sitecore.Context.Database; mediaCreatorOptions.Language = Sitecore.Context.Language; mediaCreatorOptions.Versioned = false; mediaCreatorOptions.Destination = string.Format("{0}/{1}", parentItem.Paths.FullPath, ItemUtil.ProposeValidItemName(Path.GetFileNameWithoutExtension(sampleImage))); mediaCreatorOptions.FileBased = Sitecore.Configuration.Settings.Media.UploadAsFiles; var mc = new MediaCreator(); mc.CreateFromFile(sampleImage, mediaCreatorOptions); }
public string uploadAsset(string path, string name, string extension, byte[] data, string dbName) { string filename = name + "." + extension; Database db = Database.GetDatabase(dbName); MemoryStream stream = new MemoryStream(data); MediaCreatorOptions mco = new MediaCreatorOptions(); mco.Destination = @"/sitecore/media library" + path + "/" + name; mco.Database = db; mco.IncludeExtensionInItemName = true; using (new SecurityDisabler()) { Item mediaItem = MediaManager.Creator.CreateFromStream(stream, filename, mco); return(mediaItem.ID.ToString()); } return("None"); }
public MediaItem ImportMedia(MediaItem originalItem) { if (originalItem == null) { return(null); } MediaItem mediaItem; using (MemoryStream stream2 = new MemoryStream()) { var stream = originalItem.GetMediaStream(); if (stream == null) { return(null); } stream.CopyTo(stream2); var invalidChars = new List <string> { "(", ")" }; var newItemPath = originalItem.InnerItem.Paths.FullPath; foreach (var s in invalidChars) { newItemPath = newItemPath.Replace(s, ""); } // Create the options MediaCreatorOptions options = new MediaCreatorOptions(); options.FileBased = false; options.IncludeExtensionInItemName = false; options.OverwriteExisting = true; options.Versioned = false; options.Destination = newItemPath; options.Database = Sitecore.Configuration.Factory.GetDatabase("master"); stream2.Flush(); // upload to sitecore MediaCreator creator = new MediaCreator(); mediaItem = creator.CreateFromStream(stream2, $"{originalItem.Name}.{originalItem.Extension}", options); } return(mediaItem); }
public bool UploadFile(string userName, string password, string filePath, byte[] fileContent, string database, string language) { if (!WebServiceSettings.IsEnabled(WebServiceSettings.ServiceRemoting)) { return(false); } try { if (!Login(userName, password)) { return(false); } PowerShellLog.Info($"File '{filePath}' uploaded through remoting by user: '******'"); var dirName = (Path.GetDirectoryName(filePath) ?? string.Empty).Replace('\\', '/'); if (!dirName.StartsWith(Constants.MediaLibraryPath)) { dirName = Constants.MediaLibraryPath + (dirName.StartsWith("/") ? dirName : "/" + dirName); } var mco = new MediaCreatorOptions { Database = Factory.GetDatabase(database), Language = Language.Parse(language), Versioned = Settings.Media.UploadAsVersionableByDefault, Destination = $"{dirName}/{Path.GetFileNameWithoutExtension(filePath)}" }; var mc = new MediaCreator(); using (var stream = new MemoryStream(fileContent)) { mc.CreateFromStream(stream, Path.GetFileName(filePath), mco); } } catch (Exception ex) { PowerShellLog.Error("Error during uploading file using PowerShell web service", ex); return(false); } return(true); }
/// <summary> /// Creates an item in the media library from a file. Saves it to the specified path in the media library /// </summary> /// <param name="filePath"></param> /// <param name="itemName"></param> /// <param name="fileExtension"></param> /// <param name="mediaLibraryPath">Path in sitecore to save the file</param> /// <returns></returns> public MediaItem CreateMediaLibraryItemFromFile(string filePath, string itemName, string fileExtension, string mediaLibraryPath) { Sitecore.Security.Accounts.User user = Sitecore.Security.Accounts.User.Current; MediaCreatorOptions mediaCreatorOptions = GetDefaultMediaCreatorOptions(Constants.MediaLibraryRoot + mediaLibraryPath, itemName.Replace("-", "")); //using (new Sitecore.Security.Accounts.UserSwitcher(user)) using (new Sitecore.SecurityModel.SecurityDisabler()) { try { //first, find the item, if it exists already string itempath = mediaCreatorOptions.Destination; Item mediaItem = _sitecoreMasterService.GetItem <Item>(itempath); if (mediaItem == null) { //new media item MediaItem media = MediaManager.Creator.CreateFromFile(filePath, mediaCreatorOptions); return(media); } else { //existing media item, update and increment version. MediaItem media = mediaItem; MediaItem newMedia; Stream stream = new FileStream(filePath, FileMode.Open); using (new EditContext(media)) { newMedia = media.InnerItem.Versions.AddVersion(); Media data = MediaManager.GetMedia(newMedia); var mediaStream = new MediaStream(stream, fileExtension, mediaItem); data.SetStream(mediaStream); } return(newMedia); } } catch (Exception e) { throw new Exception("CreateMediaLibraryItemFromFile: Cannot create Media Option from file = " + filePath, e); } } }
private void UploadToDatabase(string fileName, MemoryStream optimizedImage, UploadArgs args, bool isFileBased) { string validPath = FileUtil.MakePath(args.Folder, Path.GetFileName(fileName), '/'); string validMediaPath = MediaPathManager.ProposeValidMediaPath(validPath); Item createdItem = null; MediaCreatorOptions options = new MediaCreatorOptions() { Versioned = args.Versioned, Language = args.Language, OverwriteExisting = !args.Overwrite, Destination = validMediaPath, FileBased = isFileBased, AlternateText = args.GetFileParameter(fileName, "alt"), Database = null, }; options.Build(GetMediaCreatorOptionsArgs.UploadContext); createdItem = MediaManager.Creator.CreateFromStream(optimizedImage, validPath, options); }
public MediaItem AddFile(string fileName, string sitecorePath, string mediaItemName) { Assert.ArgumentNotNullOrEmpty(fileName, nameof(fileName)); // Create the options var options = new MediaCreatorOptions { FileBased = false, IncludeExtensionInItemName = true, OverwriteExisting = true, Versioned = false, Destination = sitecorePath + "/" + mediaItemName, Database = Sitecore.Context.Database }; // Now create the file var creator = new MediaCreator(); var mediaItem = creator.CreateFromFile(fileName, options); return(mediaItem); }
/// <summary> /// Create new media item /// </summary> /// <param name="filename"></param> /// <param name="altText"></param> /// <param name="filepath"></param> /// <param name="fileBytes"></param> /// <param name="errorMessage"></param> /// <returns></returns> private static Item CreateMediaItem(string filename, string originalFileNameWithExtension, string altText, string filepath, byte[] fileBytes, ref LevelLogger logger) { var createMediaItemLogger = logger.CreateLevelLogger();; try { if (fileBytes != null) { Item imageItem = null; var destPath = filepath + "/" + filename; using (var ms = new MemoryStream(fileBytes)) { var options = new MediaCreatorOptions { FileBased = false, IncludeExtensionInItemName = false, KeepExisting = false, Versioned = false, AlternateText = altText, Destination = destPath, Database = Database }; imageItem = MediaManager.Creator.CreateFromStream(ms, originalFileNameWithExtension, options); } if (imageItem != null) { return(imageItem); } } else { createMediaItemLogger.AddError(CreateMediaItemMissingDataToStream, String.Format("CreateMediaItem missing data to stream. Filename: {0}, AltText: {1}", filename, altText)); } } catch (Exception ex) { createMediaItemLogger.AddError(CreateMediaItemFailed, String.Format("CreateMediaItem failed. Filename: {0}, AltText: {1}, Errormessage: {2}", filename, altText, ex.InnerException)); } return(null); }
protected virtual Item CreateMedia(string rootPath, File mediaFile, string extension, Stream mediaStream, string altText) { using (new SecurityDisabler()) { var validItemName = ItemUtil.ProposeValidItemName(mediaFile.FileName); var filesFolder = GetItemByPath(rootPath); if (filesFolder != null) { var files = filesFolder.Children; var item = files.FirstOrDefault(f => f.Name == validItemName && DateUtil.IsoDateToDateTime(f.Fields["__Created"].Value) >= mediaFile.UpdatedDate); if (item != null) { return(item); } } var mediaOptions = new MediaCreatorOptions { Database = ContextDatabase, FileBased = false, IncludeExtensionInItemName = false, KeepExisting = true, Versioned = false, Destination = string.Concat(rootPath, "/", validItemName), }; var previewImgItem = MediaManager.Creator.CreateFromStream(mediaStream, validItemName + "." + extension, mediaOptions); //mediaOptions.AlternateText -- This is not working on the PROD. //So forciing ALT Update using below code --- This works on the PROD. //Update ALT Text previewImgItem.Editing.BeginEdit(); previewImgItem["Alt"] = altText; previewImgItem.Editing.EndEdit(); return(previewImgItem); } }
protected override string GetFullFilePath(ID itemID, string fileName, string itemPath, MediaCreatorOptions options) { Assert.ArgumentNotNull(itemID, nameof(itemID)); Assert.ArgumentNotNull(fileName, nameof(fileName)); Assert.ArgumentNotNull(itemPath, nameof(itemPath)); Assert.ArgumentNotNull(options, nameof(options)); using (new SecurityDisabler()) { var parentPath = itemPath.Substring(0, itemPath.LastIndexOf('/')); var parentId = parentPath.Substring(parentPath.LastIndexOf('/') + 1); var database = options.Database ?? Context.ContentDatabase ?? Context.Database; if (database == null) { return base.GetFullFilePath(itemID, fileName, itemPath, options); } var item = database.GetItem(parentId); if (item == null) { return base.GetFullFilePath(itemID, fileName, itemPath, options); } var fullPath = item.Paths.FullPath; var pair = FindMediaDirectory(fullPath); if (pair == null) { return base.GetFullFilePath(itemID, fileName, itemPath, options); } var folder = HostingEnvironment.MapPath(Path.Combine(pair.Value.Value, fullPath.Substring(pair.Value.Key.Length).Trim("/\\".ToCharArray()))); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } return FileUtil.GetUniqueFilename(Path.Combine(folder, Path.GetFileName(fileName))); } }
/// <summary> /// Unpacks to database. /// /// </summary> private void UnpackToDatabase(List <S3MediaUploadResult> list) { Assert.ArgumentNotNull((object)list, "list"); string str = FileUtil.MapPath(TempFolder.GetFilename("temp.zip")); this.File.SaveAs(str); try { using (ZipReader zipReader = new ZipReader(str)) { foreach (ZipEntry zipEntry in zipReader.Entries) { if (!zipEntry.IsDirectory) { S3MediaUploadResult S3MediaUploadResult = new S3MediaUploadResult(); list.Add(S3MediaUploadResult); S3MediaUploadResult.Path = FileUtil.MakePath(this.Folder, zipEntry.Name, '/'); S3MediaUploadResult.ValidMediaPath = MediaPathManager.ProposeValidMediaPath(S3MediaUploadResult.Path); MediaCreatorOptions options = new MediaCreatorOptions() { Language = this.Language, Versioned = this.Versioned, KeepExisting = !this.Overwrite, Destination = S3MediaUploadResult.ValidMediaPath, FileBased = this.FileBased, Database = this.Database }; options.Build(GetMediaCreatorOptionsArgs.UploadContext); Stream stream = zipEntry.GetStream(); S3MediaUploadResult.Item = MediaManager.Creator.CreateFromStream(stream, S3MediaUploadResult.Path, options); } } } } finally { FileUtil.Delete(str); } }
/// <summary> /// Uploads to database. /// /// </summary> private void UploadToDatabase(List <S3MediaUploadResult> list) { Assert.ArgumentNotNull((object)list, "list"); var S3MediaUploadResult = new S3MediaUploadResult(); list.Add(S3MediaUploadResult); S3MediaUploadResult.Path = FileUtil.MakePath(this.Folder, Path.GetFileName(this.File.FileName), '/'); S3MediaUploadResult.ValidMediaPath = MediaPathManager.ProposeValidMediaPath(S3MediaUploadResult.Path); MediaCreatorOptions options = new MediaCreatorOptions { Versioned = this.Versioned, Language = this.Language, KeepExisting = !this.Overwrite, Destination = S3MediaUploadResult.ValidMediaPath, FileBased = this.FileBased, AlternateText = this.AlternateText, Database = this.Database }; options.Build(GetMediaCreatorOptionsArgs.UploadContext); S3MediaUploadResult.Item = MediaManager.Creator.CreateFromStream(this.File.InputStream, S3MediaUploadResult.Path, options); }
private void CommitContent() { if (!contentCommitted) { contentCommitted = true; if (mediaBlob) { var mc = new MediaCreator(); var mco = new MediaCreatorOptions() { Database = Factory.GetDatabase(database), FileBased = fileBased, Versioned = versioned }; if (!string.IsNullOrEmpty(language)) { mco.Language = LanguageManager.GetLanguage(language); } mc.AttachStreamToMediaItem(Stream, PathUtilities.GetSitecorePath(path), PathUtilities.GetLeafFromPath(path) + extension, mco); } } }
public bool UploadFile(string userName, string password, string filePath, byte[] fileContent, string database, string language) { if (!WebServiceSettings.ServiceEnabledRemoting) { return(false); } try { Login(userName, password); var dirName = (Path.GetDirectoryName(filePath) ?? string.Empty).Replace('\\', '/'); if (!dirName.StartsWith(Constants.MediaLibraryPath)) { dirName = Constants.MediaLibraryPath + (dirName.StartsWith("/") ? dirName : "/" + dirName); } var mco = new MediaCreatorOptions(); mco.Database = Factory.GetDatabase(database); mco.Language = Language.Parse(language); mco.Versioned = Settings.Media.UploadAsVersionableByDefault; mco.Destination = string.Format("{0}/{1}", dirName, Path.GetFileNameWithoutExtension(filePath)); var mc = new MediaCreator(); using (var stream = new MemoryStream(fileContent)) { mc.CreateFromStream(stream, Path.GetFileName(filePath), mco); } } catch (Exception ex) { LogUtils.Error("Error during uploading file using PowerShell web service", ex); return(false); } return(true); }
public JsonResult Upload(string database = "master", string mediaFolderPath = "/sitecore/media library/Uploaded Files") { SitecoreViewModelResult result = new SitecoreViewModelResult(); try { Database db = Factory.GetDatabase(database); if (db == null) { return(result); } foreach (string file in Request.Files) { HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase; if (hpf.ContentLength == 0 || !ValidateFile(hpf, result)) { continue; } string fileName = ItemUtil.ProposeValidItemName(Path.GetFileName(hpf.FileName)); MediaCreatorOptions md = new MediaCreatorOptions(); md.Destination = StringUtil.EnsurePostfix('/', StringUtil.EnsurePrefix('/', mediaFolderPath)) + fileName; md.Database = db; using (new SecurityDisabler()) { Item mediaItem = MediaManager.Creator.CreateFromStream(hpf.InputStream, fileName, md); } } } catch (Exception ex) { Log.Error("could not upload", ex, this); } return(result); }
public MediaItem ImportImage(string url, string fileName, string newPath) { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; if (request == null) { return(null); } try { // download data HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream stream1 = response.GetResponseStream(); MemoryStream stream2 = new MemoryStream(); stream1.CopyTo(stream2); // Create the options MediaCreatorOptions options = new MediaCreatorOptions(); options.FileBased = false; options.IncludeExtensionInItemName = false; options.KeepExisting = false; options.Versioned = false; options.Destination = newPath; options.Database = Sitecore.Configuration.Factory.GetDatabase("master"); // upload to sitecore MediaCreator creator = new MediaCreator(); MediaItem mediaItem = creator.CreateFromStream(stream2, fileName, options); response.Close(); return(mediaItem); } catch (WebException ex) { return(null); } }
public bool UploadPhoto(Stream fileStream, string fileName) { try { var path = TranslateHelper.TranslateMessage(DictionaryKeys.PhotoSaveTo.Path) + fileName.Split('.')[0]; using (var memoryStream = new MemoryStream()) { fileStream.CopyTo(memoryStream); var mediaCreator = new MediaCreator(); var options = new MediaCreatorOptions { Versioned = false, IncludeExtensionInItemName = false, Database = Context.Database, Destination = path }; using (new SecurityDisabler()) { var item = mediaCreator.CreateFromStream(memoryStream, fileName, options); var userProfile = Context.User.Profile; if (userProfile != null) { userProfile.Icon = MediaManager.GetMediaUrl(item); Context.User.Profile.Save(); } } } return(true); } catch { return(false); } }
private MediaItem ImportMediaItem(Stream mediaStream, string fileName, string newPath) { MediaItem mediaItem; using (MemoryStream stream2 = new MemoryStream()) { mediaStream.CopyTo(stream2); // Create the options MediaCreatorOptions options = new MediaCreatorOptions(); options.FileBased = false; options.IncludeExtensionInItemName = false; options.OverwriteExisting = true; options.Versioned = false; options.Destination = newPath; options.Database = Sitecore.Configuration.Factory.GetDatabase("master"); stream2.Flush(); // upload to sitecore MediaCreator creator = new MediaCreator(); mediaItem = creator.CreateFromStream(stream2, fileName, options); } return(mediaItem); }
private static void ProcessMediaUpload(Stream content, Database db, string itemParam, string entryName, bool skipExisting = false) { var mediaItem = (MediaItem)db.GetItem(itemParam) ?? db.GetItem(itemParam.TrimStart('/', '\\')) ?? db.GetItem(ApplicationSettings.MediaLibraryPath + itemParam); if (mediaItem == null) { var filename = itemParam.TrimEnd('/', '\\').Replace('\\', '/'); var dirName = (Path.GetDirectoryName(filename) ?? string.Empty).Replace('\\', '/'); if (!dirName.StartsWith(Constants.MediaLibraryPath)) { dirName = Constants.MediaLibraryPath + (dirName.StartsWith("/") ? dirName : "/" + dirName); } if (!String.IsNullOrEmpty(entryName)) { dirName += "/" + Path.GetDirectoryName(entryName).Replace('\\', '/'); filename = Path.GetFileName(entryName); } var mco = new MediaCreatorOptions { Database = db, Versioned = Settings.Media.UploadAsVersionableByDefault, Destination = $"{dirName}/{Path.GetFileNameWithoutExtension(filename)}", }; var mc = new MediaCreator(); using (var ms = new MemoryStream()) { content.CopyTo(ms); mc.CreateFromStream(ms, Path.GetFileName(filename), mco); } } else { if (skipExisting) return; var mediaUri = MediaUri.Parse(mediaItem); var media = MediaManager.GetMedia(mediaUri); using (var ms = new MemoryStream()) { content.CopyTo(ms); using (new EditContext(mediaItem, SecurityCheck.Disable)) { using (var mediaStream = new MediaStream(ms, media.Extension, mediaItem)) { media.SetStream(mediaStream); } } } } }
private MediaItem AddTestImageToMaster(string parent) { var masterDatabase = Sitecore.Configuration.Factory.GetDatabase("master"); var options = new MediaCreatorOptions { Database = masterDatabase, Destination = parent }; return MediaManager.Creator.CreateFromFile("~/TestResources/visual_list.png", options); }
private void NotifyUsers(ImportOptions options, int num, int num2, int num3, int num4, string pathToEmailReport) { try { Sitecore.Data.Database master = Sitecore.Modules.EmailCampaign.Util.GetContentDb(); MediaCreatorOptions md = new MediaCreatorOptions(); md.Destination = @"/sitecore/media library/Files/" + Sitecore.Configuration.Settings.GetSetting("RecipientImporterExt.PathToEmailReport", "/temp")+"/" + Path.GetFileNameWithoutExtension(pathToEmailReport); // Set options md.Database = master; // Set options MediaItem mediaItem = null; using (new SecurityDisabler()) // Use the SecurityDisabler object to override the security settings { // Create Media in database from file mediaItem = MediaManager.Creator.CreateFromFile(pathToEmailReport, md); } Sitecore.Data.Items.Item itemToSend = master.GetItem(Sitecore.Configuration.Settings.GetSetting("RecipientImporterExt.MessagePath", "/sitecore/content/Home/Email Campaign/Messages/Service Messages/Self-Service Subscription/Subscription Notification")); MessageItem messageItem = Sitecore.Modules.EmailCampaign.Factory.GetMessage(itemToSend); messageItem.Body = string.Format("Recipients imported: {0} <br/> E-mail addresses already exist: {1} <br/> E-mail addresses not provided: {2} <br/> Users not imported as required fields not available: {3}" + " <br/> You can check report file with the failed records here: {4}. <br/> Import finished at " + DateTime.Now.ToString(@"d/M/yyyy hh:mm:ss tt"), num, num2, num3, num4, pathToEmailReport); messageItem.Subject = "User import from " + Path.GetFileNameWithoutExtension(options.Filename) + " finished."; if (mediaItem != null) { messageItem.Attachments.Add(mediaItem); } SendingManager sendingManager = new SendingManager(messageItem); ListString usernamesToSend = new ListString(Sitecore.Configuration.Settings.GetSetting("RecipientImporterExt.SendTo", "sitecore\\admin"), ','); if (usernamesToSend.Count == 0) { Log.Info("RecipientImporterExt debug info: no users configured to send email to. Email will be sent only to the context user.", this); // return result; } else { foreach (string nameString in usernamesToSend) { Contact contactToSend = Sitecore.Modules.EmailCampaign.Factory.GetContactFromName(nameString); if (contactToSend != null) { Log.Info("RecipientImporterExt debug info: Sending notification about the import to " + contactToSend.Profile.Email, this); sendingManager.SendStandardMessage(contactToSend); } } } User user = Sitecore.Context.User; if (user != null && !usernamesToSend.Contains(user.Name)) { string username = user.Name; Contact contactToSend = Sitecore.Modules.EmailCampaign.Factory.GetContactFromName(username); if (contactToSend != null) { Log.Info("RecipientImporterExt debug info: Sending notification about the import to " + username, this); sendingManager.SendStandardMessage(contactToSend); } } } catch (Exception e) { Logging.LogError(e); } }
/// <summary> /// Uploads to database. /// /// </summary> private void UploadToDatabase(List<S3MediaUploadResult> list) { Assert.ArgumentNotNull((object)list, "list"); var S3MediaUploadResult = new S3MediaUploadResult(); list.Add(S3MediaUploadResult); S3MediaUploadResult.Path = FileUtil.MakePath(this.Folder, Path.GetFileName(this.File.FileName), '/'); S3MediaUploadResult.ValidMediaPath = MediaPathManager.ProposeValidMediaPath(S3MediaUploadResult.Path); MediaCreatorOptions options = new MediaCreatorOptions { Versioned = this.Versioned, Language = this.Language, KeepExisting = !this.Overwrite, Destination = S3MediaUploadResult.ValidMediaPath, FileBased = this.FileBased, AlternateText = this.AlternateText, Database = this.Database }; options.Build(GetMediaCreatorOptionsArgs.UploadContext); S3MediaUploadResult.Item = MediaManager.Creator.CreateFromStream(this.File.InputStream, S3MediaUploadResult.Path, options); }
private void CommitContent() { if (!contentCommitted) { contentCommitted = true; if (mediaBlob) { var mc = new MediaCreator(); var mco = new MediaCreatorOptions() { Database = Factory.GetDatabase(database), FileBased = fileBased, Versioned = versioned }; if (!string.IsNullOrEmpty(language)) { mco.Language = LanguageManager.GetLanguage(language); } mc.AttachStreamToMediaItem(Stream, PathUtilities.GetSitecorePath(path), PathUtilities.GetLeafFromPath(path) + extension, mco); } } }
private static void ProcessMediaUpload(Stream content, Database db, string path, bool skipExisting = false) { var guidPattern = @"(?<id>{[a-z0-9]{8}[-][a-z0-9]{4}[-][a-z0-9]{4}[-][a-z0-9]{4}[-][a-z0-9]{12}})"; path = path.Replace('\\', '/').TrimEnd('/'); path = (path.StartsWith("/") ? path : "/" + path); var originalPath = path; var dotIndex = path.IndexOf(".", StringComparison.OrdinalIgnoreCase); if (dotIndex > -1) { path = path.Substring(0, dotIndex); } if (!path.StartsWith(Constants.MediaLibraryPath)) { path = Constants.MediaLibraryPath + (path.StartsWith("/") ? path : "/" + path); } var mediaItem = (MediaItem)db.GetItem(path); if (mediaItem == null && Regex.IsMatch(originalPath, guidPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase)) { var id = Regex.Match(originalPath, guidPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase).Value; mediaItem = db.GetItem(id); } if (mediaItem == null) { var fileName = Path.GetFileName(originalPath); var itemName = Path.GetFileNameWithoutExtension(path); var dirName = (Path.GetDirectoryName(path) ?? string.Empty).Replace('\\', '/'); if (String.IsNullOrEmpty(fileName)) { PowerShellLog.Warn($"The filename cannot be determined for the entry {fileName}."); return; } var mco = new MediaCreatorOptions { Database = db, Versioned = Settings.Media.UploadAsVersionableByDefault, Destination = $"{dirName}/{itemName}", }; var mc = new MediaCreator(); using (var ms = new MemoryStream()) { content.CopyTo(ms); mc.CreateFromStream(ms, fileName, mco); } } else { if (skipExisting) { return; } var mediaUri = MediaUri.Parse(mediaItem); var media = MediaManager.GetMedia(mediaUri); using (var ms = new MemoryStream()) { content.CopyTo(ms); using (new EditContext(mediaItem, SecurityCheck.Disable)) { using (var mediaStream = new MediaStream(ms, media.Extension, mediaItem)) { media.SetStream(mediaStream); } } } } }
protected override string GetFullFilePath(ID itemID, string fileName, string itemPath, MediaCreatorOptions options) { Assert.ArgumentNotNull(itemID, nameof(itemID)); Assert.ArgumentNotNull(fileName, nameof(fileName)); Assert.ArgumentNotNull(itemPath, nameof(itemPath)); Assert.ArgumentNotNull(options, nameof(options)); using (new SecurityDisabler()) { var parentPath = itemPath.Substring(0, itemPath.LastIndexOf('/')); var parentId = parentPath.Substring(parentPath.LastIndexOf('/') + 1); var database = options.Database ?? Context.ContentDatabase ?? Context.Database; if (database == null) { return base.GetFullFilePath(itemID, fileName, itemPath, options); } var provider = JsonDataProvider.Instances[database.Name]; if (provider == null) { return base.GetFullFilePath(itemID, fileName, itemPath, options); } ID id; if (!ID.TryParse(parentId, out id)) { return base.GetFullFilePath(itemID, fileName, itemPath, options); } foreach (var fileMapping in provider.Mappings.OfType<IFileMapping>()) { if (fileMapping.ReadOnly) { continue; } var mediaFolderPath = fileMapping.MediaFolderPath; if (string.IsNullOrEmpty(mediaFolderPath)) { continue; } if (!fileMapping.AcceptsNewChildrenOf(id)) { continue; } var item = database.GetItem(itemID); Assert.IsNotNull(item, "item"); itemPath = item.Parent.Paths.FullPath; var folder = Path.Combine(mediaFolderPath, itemPath.Substring("/sitecore/media library".Length).TrimStart('/')).Replace("/", "\\"); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } var filePath = FileUtil.GetUniqueFilename(Path.Combine(folder, Path.GetFileName(fileName))); var webRootPath = MainUtil.MapPath("/"); if (!filePath.StartsWith(webRootPath, StringComparison.OrdinalIgnoreCase)) { return filePath; } return filePath.Substring(webRootPath.Length - 1).Replace("\\", "/"); } return base.GetFullFilePath(itemID, fileName, itemPath, options); } }
private void UploadToS3(List<S3MediaUploadResult> list) { Assert.ArgumentNotNull(list, "list"); var upload = new S3MediaUploadResult(); list.Add(upload); upload.Path = FileUtil.MakePath(this.Folder, Path.GetFileName(this.File.FileName), '/'); upload.ValidMediaPath = MediaPathManager.ProposeValidMediaPath(upload.Path); MediaCreatorOptions options = new MediaCreatorOptions { Versioned = this.Versioned, Language = this.Language, KeepExisting = !this.Overwrite, Destination = upload.ValidMediaPath, FileBased = this.FileBased, AlternateText = this.AlternateText, Database = this.Database }; options.Build(GetMediaCreatorOptionsArgs.UploadContext); var item = MediaManager.Creator.CreateFromStream(new MemoryStream(), upload.Path, options); upload.Item = item; S3Client.SendImageToS3(item.ID.ToString(), File.InputStream); }
public bool UploadFile(string userName, string password, string filePath, byte[] fileContent, string database, string language) { if (!WebServiceSettings.ServiceEnabledRemoting) { return false; } try { Login(userName, password); var dirName = (Path.GetDirectoryName(filePath) ?? string.Empty).Replace('\\', '/'); if (!dirName.StartsWith(Constants.MediaLibraryPath)) { dirName = Constants.MediaLibraryPath + (dirName.StartsWith("/") ? dirName : "/" + dirName); } var mco = new MediaCreatorOptions(); mco.Database = Factory.GetDatabase(database); mco.Language = Language.Parse(language); mco.Versioned = Settings.Media.UploadAsVersionableByDefault; mco.Destination = string.Format("{0}/{1}", dirName, Path.GetFileNameWithoutExtension(filePath)); var mc = new MediaCreator(); using (var stream = new MemoryStream(fileContent)) { mc.CreateFromStream(stream, Path.GetFileName(filePath), mco); } } catch (Exception ex) { LogUtils.Error("Error during uploading file using PowerShell web service", ex); return false; } return true; }
/// <summary> /// Attach new image to media item /// </summary> /// <param name="imageItem"></param> /// <param name="filename"></param> /// <param name="imageBytes"></param> /// <param name="altText"></param> /// <param name="destPath"></param> /// <param name="errorMessage"></param> private static void AttachNewImageToMediaItem(MediaItem imageItem, string filename, byte[] imageBytes, string altText, string destPath, ref LevelLogger logger) { try { destPath = destPath + "/" + filename; if (imageBytes != null) { using (var ms = new MemoryStream(imageBytes)) { var options = new MediaCreatorOptions { FileBased = false, IncludeExtensionInItemName = false, KeepExisting = false, Versioned = false, AlternateText = altText, Destination = destPath, Database = Database }; MediaManager.Creator.AttachStreamToMediaItem(ms, destPath, filename, options); } } } catch (Exception ex) { logger.AddError(ExceptionTryingToAttachNewImageToExistingMediaitem, String.Format("Error trying to attach new image to existing mediaitem: InnerException {0}. Message {1}", ex.InnerException, ex.Message)); } }
/// <summary> /// Unpacks to database. /// /// </summary> private void UnpackToDatabase(List<S3MediaUploadResult> list) { Assert.ArgumentNotNull((object)list, "list"); string str = FileUtil.MapPath(TempFolder.GetFilename("temp.zip")); this.File.SaveAs(str); try { using (ZipReader zipReader = new ZipReader(str)) { foreach (ZipEntry zipEntry in zipReader.Entries) { if (!zipEntry.IsDirectory) { S3MediaUploadResult S3MediaUploadResult = new S3MediaUploadResult(); list.Add(S3MediaUploadResult); S3MediaUploadResult.Path = FileUtil.MakePath(this.Folder, zipEntry.Name, '/'); S3MediaUploadResult.ValidMediaPath = MediaPathManager.ProposeValidMediaPath(S3MediaUploadResult.Path); MediaCreatorOptions options = new MediaCreatorOptions() { Language = this.Language, Versioned = this.Versioned, KeepExisting = !this.Overwrite, Destination = S3MediaUploadResult.ValidMediaPath, FileBased = this.FileBased, Database = this.Database }; options.Build(GetMediaCreatorOptionsArgs.UploadContext); Stream stream = zipEntry.GetStream(); S3MediaUploadResult.Item = MediaManager.Creator.CreateFromStream(stream, S3MediaUploadResult.Path, options); } } } } finally { FileUtil.Delete(str); } }
public XmlRpcStruct newMediaObject(string blogid, string username, string password, XmlRpcStruct rpcstruct) { // Check user validation Authenticate(username, password); var name = rpcstruct["name"].ToString(); var type = rpcstruct["type"].ToString(); var media = (byte[])rpcstruct["bits"]; var blogName = string.Empty; var currentBlog = ContentHelper.GetContentDatabase().GetItem(blogid); blogName = currentBlog.Name; // Get filename var fileName = Path.GetFileName(name); var imageName = ItemUtil.ProposeValidItemName(Path.GetFileNameWithoutExtension(fileName)); // Create strem from byte array var memStream = new MemoryStream(media); var md = new MediaCreatorOptions(); md.Destination = string.Join("/", new string[]{Constants.Paths.WeBlogMedia, blogName, imageName}); md.Database = ContentHelper.GetContentDatabase(); md.AlternateText = imageName; // Create mediaitem var mediaItem = MediaManager.Creator.CreateFromStream(memStream, fileName, md); // Publish mediaitem to web database ContentHelper.PublishItemAndRequiredAncestors(mediaItem.ID); // Close stream memStream.Close(); memStream.Dispose(); // Get the mediaitem url and return it var rstruct = new XmlRpcStruct(); var options = new MediaUrlOptions() { AbsolutePath = false, UseItemPath = false }; rstruct.Add("url", MediaManager.GetMediaUrl(mediaItem, options)); return rstruct; }
protected virtual void UploadFile([Diagnostics.NotNull] IEmitContext context, [Diagnostics.NotNull] Projects.Items.Item mediaItem, [Diagnostics.NotNull] MediaFile mediaFile) { var database = Factory.GetDatabase(mediaItem.DatabaseName); var name = mediaItem.ItemName; var options = new MediaCreatorOptions { AlternateText = name, Database = database, FileBased = false, IncludeExtensionInItemName = false, // keep existing item - but the KeepExisting flag is flipped - must be an issue in the CMS KeepExisting = false, Language = LanguageManager.DefaultLanguage, Versioned = false, Destination = mediaItem.ItemIdOrPath }; var destinationItem = database.GetItem(mediaItem.ItemIdOrPath); if (destinationItem != null && destinationItem.ID.ToGuid() != mediaItem.Uri.Guid) { // whoops - item has wrong ID destinationItem.Delete(); destinationItem = null; } var uploadMedia = true; if (!context.ForceUpdate && destinationItem != null) { var item = new MediaItem(destinationItem); var fileInfo = new FileInfo(mediaFile.Snapshots.First().SourceFile.AbsoluteFileName); uploadMedia = (item.Size != fileInfo.Length); } if (destinationItem == null) { // create parent path of media folders before uploading var parentPath = PathHelper.GetItemParentPath(mediaItem.ItemIdOrPath); var mediaFolderTemplate = new TemplateItem(database.GetItem(TemplateIDs.MediaFolder)); var parent = database.CreateItemPath(parentPath, mediaFolderTemplate); // create media item with correct ID, but probably wrong template ItemManager.AddFromTemplate(name, TemplateIDs.Folder, parent, new Data.ID(mediaItem.Uri.Guid)); } if (uploadMedia) { using (var stream = new FileStream(mediaFile.Snapshots.First().SourceFile.AbsoluteFileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { var item = MediaManager.Creator.CreateFromStream(stream, "/upload/" + Path.GetFileName(mediaFile.Snapshots.First().SourceFile.AbsoluteFileName), options); if (item == null) { throw new EmitException(Texts.Failed_to_upload_media, mediaFile.Snapshots.First()); } if (mediaItem.Uri.Guid != item.ID.ToGuid()) { context.Trace.TraceError(Msg.E1005, Texts.Media_item_created_with_wrong_ID, new SnapshotTextNode(mediaFile.Snapshots.First()), $"{item.ID} != {mediaItem.Uri.Guid.Format()}"); } } } var itemEmitter = new ItemEmitter(); itemEmitter.Emit(context, mediaItem); }
/// <summary> /// Create new media item /// </summary> /// <param name="filename"></param> /// <param name="altText"></param> /// <param name="filepath"></param> /// <param name="fileBytes"></param> /// <param name="errorMessage"></param> /// <returns></returns> private static Item CreateMediaItem(string filename, string originalFileNameWithExtension, string altText, string filepath, MemoryStream memoryStream, ref LevelLogger logger) { var createMediaItemLogger = logger.CreateLevelLogger(); try { if (memoryStream != null) { Item imageItem = null; var destPath = filepath + "/" + filename; var options = new MediaCreatorOptions { FileBased = false, IncludeExtensionInItemName = false, KeepExisting = false, Versioned = false, AlternateText = altText, Destination = destPath, Database = Database }; imageItem = MediaManager.Creator.CreateFromStream(memoryStream, originalFileNameWithExtension, options); if (imageItem != null) { return imageItem; } } else { createMediaItemLogger.AddError(CreateMediaItemMissingDataToStream, String.Format("CreateMediaItem missing data to stream. Filename: {0}, AltText: {1}", filename, altText)); } } catch (Exception ex) { createMediaItemLogger.AddError(CreateMediaItemFailed, String.Format("CreateMediaItem failed. Filename: {0}, AltText: {1}, Errormessage: {2}", filename, altText, ex.Message)); } return null; }