Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I upload a file to the Sitecore media library in code using an ASP FileUpload control?

Here is what I have tried and it doesn't seem to work. I don't get any errors, but it doesn't seem to add the file to the media library either.

using(new Sitecore.SecurityModel.SecurityDisabler())
{
  if(myFileControl.HasFile)
  {
    MediaCreatorOptions _options = new MediaCreatorOptions();
    _options.Database = Factory.GetDatabase("master");
    _options.FileBased = false;
    _options.IncludeExtensionInItemName = false;
    _options.KeepExisting = false;
    _options.Versioned = false;
    _options.Destination = "/sitecore/media library";
    MediaItem _newFile = MediaManager.Creator.CreateFromStream(myFileControl.FileContent, myFileControl.FileName, _options);
  }
}

My biggest issue is that I don't really understand what some of the different parameters and properties do. What is the "Destination" property for the MediaCreatorOptions? Is it supposed to be just a folder? Is it supposed to have the item name also? What are the three parameters for the CreateFromStream method? The first one seems to be the Stream - I get that. But the second was says "FileName". What is this supposed to be? If I am creating from a Stream why do I need to tell Sitecore the FileName?

Any help would be appreciated.

like image 472
Corey Burnett Avatar asked Jan 23 '12 15:01

Corey Burnett


1 Answers

I think that your problem here is that you're not using the proper options for the Sitecore API call. You don't have a real destination.. which is where you would specify the Sitecore item that will become your item... not just a folder. It looks like you're trying to create the media library item.

Per the Content API Book on SDN:

How to Create Media Items Using APIs

You can use the Sitecore.Resources.Media.MediaCreator and Sitecore.Resources.Media.MediaCreatorOptions classes to create media items from files. For example, to create the media item /Sitecore/Media Library/Images/Sample in the Master database from the file C:\temp\sample.jpg:

Sitecore.Resources.Media.MediaCreatorOptions options =  new Sitecore.Resources.Media.MediaCreatorOptions();
options.Database = Sitecore.Configuration.Factory.GetDatabase("master");
options.Language = Sitecore.Globalization.Language.Parse(Sitecore.Configuration.Settings.DefaultLanguage);
options.Versioned = Sitecore.Configuration.Settings.Media.UploadAsVersionableByDefault;
options.Destination = "/sitecore/media library/images/Sample";
options.FileBased = Sitecore.Configuration.Settings.Media.UploadAsFiles;
Sitecore.Resources.Media.MediaCreator creator = new Sitecore.Resources.Media.MediaCreator();
Sitecore.Data.Items.MediaItem sample = creator.CreateFromFile(@"C:\temp\sample.jpg",options)
like image 171
divamatrix Avatar answered Sep 17 '22 15:09

divamatrix