Using the IContentManager to upload an image to the media library

Topics: Writing modules
Aug 9, 2015 at 12:03 PM
Edited Aug 9, 2015 at 12:03 PM
In the migration class, I would like to add some content (images) to the media library/folder, e.g. standard car manufactor logos that should be provided by the module.
Additionally, the logos should reside in a subfolder.

I try to figure out how to accomplish this.

My first try is this (maybe this is a completely wrong way):

I found that there is an IContentManager interface, but I do get a NullReferenceException when calling the New method (the _contentManager itself references to a DefaultContentManager implementation):
var contentItem = _contentManager.New("Manufactor");
The NullReferenceException is caused by an empty httpContext parameter in WorkContextAccessor.cs:88 of Orchard 1.9.1:
httpContext.Items[workContextKey] = _workContext;
After debugging into the framework, it seems that this line should provide the context: (MvcModule.cs:56 of Orchard 1.9.1):
var httpContextBase = context.Resolve<IHttpContextAccessor>().Current();
Any idea what I am doing wrong?
Aug 9, 2015 at 12:41 PM
Edited Aug 9, 2015 at 2:03 PM
I've just seen that there is already an issue for that:

Sorry for my "duplicate" post.

The provided patch of jersiovic works for me, the exception is gone:
Aug 9, 2015 at 2:07 PM
Edited Aug 10, 2015 at 5:22 AM
I am now trying to upload an image to the image library with the content manager. Is that the right tool, or is it meant only for creating content items?
Aug 10, 2015 at 7:00 AM
To upload images to the media library as well as turning them into 'content items' (so you can actually see them in the Media in the dashboard) you can use the MediaLibrary services. There are already services for that, so why write it yourself. Just add a reference in your module to 'Orchard.MediaLibrary' and inject the IMediaLibraryService to make use of the functionality.
Marked as answer by mcmcod120 on 8/10/2015 at 1:42 AM
Aug 10, 2015 at 8:44 AM
Thank you sanderg.

Here's my code to share with others:
using (var stream = new FileStream(@"c:\Users\mcmco\Desktop\MyLogo.png",FileMode.Open, FileAccess.Read, FileShare.Read)) {
                MediaPart mediaPart = _mediaLibraryService.ImportMedia(stream, "Logo-Images", "MyLogo.png");
As I learned, the "ImportMedia" uploads the image to the server and creates a MediaPart which is returned. It is necessary to save the MediaPart with the ContentManager by calling "Create".