3

I have a scenario where I need site visitors to be able to upload media items via CD server. My plan is to upload to web database first and use EventQueues to then have the CM server fetch the serialized media item and write it to the master database.

For this approach to be viable though I need to be able to specify the master instance of the item's id to match the web instance.

Currently to create media items I have the following extension method...

public static MediaItem CreateMediaItem(this Item parentItem, HttpPostedFileBase file, Sitecore.Data.Database database)
{
    try
    {
        var fileName = ItemUtil.ProposeValidItemName(Path.GetFileNameWithoutExtension(file.FileName));

        var options = new Sitecore.Resources.Media.MediaCreatorOptions
        {
            Database = database,
            Destination = parentItem.Paths.Path + "/" + Path.GetFileNameWithoutExtension(file.FileName),
            IncludeExtensionInItemName = false,
            KeepExisting = true,
            Versioned = false,
            FileBased = false,
            AlternateText = Path.GetFileNameWithoutExtension(file.FileName)
        };

        var creator = new Sitecore.Resources.Media.MediaCreator();

        return (MediaItem)creator.CreateFromStream(file.InputStream, file.FileName, options);

    }
    catch(Exception ex)
    {
            //handle it
    }
} 

Is there any way to utilize MediaCreator to specify what I want the id to be?

1 Answer 1

4

From what I know, it's not possible with MediaCreator class.

What you could try instead is to create an item first using ItemManager like:

Item newItem = ItemManager.CreateItem(newItemName, parentItem, templateID, newItemID);

And then use MediaCreator.AttachStreamToMediaItem method with

MediaCreatorOptions.KeepExisting = false;
// or better
MediaCreatorOptions.OverwriteExisting = true;

Your code will first create the empty media item with specific ID and then will override it with the data from the stream.

3
  • Thanks Marek, I'll give this a try and report back
    – Sean T
    Mar 20, 2019 at 13:32
  • I've found a MediaCreator.AttachStreamToMediaItem() method, looks like it is what I'm after when using your suggestion. If you want to update your answer I'll accept :)
    – Sean T
    Mar 20, 2019 at 13:38
  • Answer updated.
    – Marek Musielak
    Mar 20, 2019 at 14:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.