Search code examples
c#sitecoresitecore8

Sitecore: Saving images in media library from url


To download and save an image in media library I am using following code. I can see an item is created in media library but it has no media.

using (WebClient webClient = new WebClient())
{
    byte[] data = webClient.DownloadData("https://myurl/images?id="+12345);
    Stream memoryStream = new MemoryStream(data);
    var options = new Sitecore.Resources.Media.MediaCreatorOptions
    {
        FileBased = false,
        OverwriteExisting = true,
        Versioned = true,
        IncludeExtensionInItemName = true,
        Destination = Factory.GetDatabase("master").GetItem(Settings.GetSetting("ProfilePicturesFolderItemId")).Paths.Path + "/" + "12345",
        Database = Factory.GetDatabase("master"),
        AlternateText = userProfileItem.Name
    };


    using (new SecurityDisabler())
    {
        var creator = new Sitecore.Resources.Media.MediaCreator();
        creator.CreateFromStream(memoryStream, v1ImageId, options);
    }
}

In the Media folder i can see an item with name, "12345" but there is no media.


Solution

  • From what I remember, when you pass the Destination in options, it has to contain the new name of the item and it should be the same as the second argument in CreateFromStream method call just without extension:

    using (WebClient webClient = new WebClient())
    {
        string filename = "SOMEFILENAME";
        string extension = ".png"; // or whatever is the extension
    
        byte[] data = webClient.DownloadData(imageUrl);
        Stream memoryStream = new MemoryStream(data);
        var options = new Sitecore.Resources.Media.MediaCreatorOptions
        {
            FileBased = false,
            OverwriteExisting = true,
            Versioned = true,
            IncludeExtensionInItemName = true,
            Destination = Factory.GetDatabase("master").GetItem(Settings.GetSetting("ProfilePicturesFolderItemId")).Paths.Path + "/" + filename,
            Database = Factory.GetDatabase("master"),
            AlternateText = userProfileItem.Name
        };
    
    
        using (new SecurityDisabler())
        {
            var creator = new Sitecore.Resources.Media.MediaCreator();
            creator.CreateFromStream(memoryStream, filename + extension, options);
        }
    }