IMediaLibraryService.ImportMedia saves file but does not import media into library.

Topics: Customizing Orchard
Oct 23, 2015 at 12:05 AM
I have a custom module which supports uploading an image, with the intention of importing the image into the Media Library, and also adding the image as a MediaPart to the MediaParts collection of a MediaLibraryPicker field on a content item.

In the code snippet below, "file" is the uploaded file of type HttpPostedFileBase.
var mediaPart = _mediaLibraryService.ImportMedia(file.InputStream, folderPath, file.FileName);
The file is correctly saved to the file system in the specified location.

However, the file never appears in the Media Library. Why not?

Also, the resulting MediaPart looks great, but when I add it to the MediaParts collection of my content item's MediaLibraryPicker field, it isn't persisted. Perhaps because the content item isn't evidently changed merely by adding an item to the MediaParts collection; but what is the solution? I do not want to publish the content item; it needs to remain in a draft state at this point.

Any clues would be most appreciated.
Oct 23, 2015 at 2:59 AM
To extend this, if anyone has a clue on how to programmatically add a newly uploaded image to the list of MediaParts on a MediaLibraryPickerField, I would be extremely grateful. It's strange how difficult this seems to be.
Dec 10, 2015 at 2:06 PM
You need to call Create method:
      var stream = File.Open(file.FullName, FileMode.Open, FileAccess.Read);
                    var mediaPart = _mediaLibraryService.ImportMedia(stream, destDirPath.Replace("\\", "/"), file.Name, "");
                    _contentManager.Create(mediaPart);
Marked as answer by ayitey on 12/14/2015 at 12:11 AM
Dec 14, 2015 at 8:11 AM
Thank you! That seems incredibly obvious, doesn't it?
Dec 18, 2015 at 9:47 PM
That is Orchard CMS: world of undocumented abilities, and it is very non-obvious in many cases.
Orchard is nerdy like Linux and that is pay off for free price and high flexibility.
Better way to use Orchard to check sources of same functions in CMS itself and in modules created by community.