Upload multiple custom media types
Enable multiple custom media upload
You probably often had to add some additional ptoperties to a media type. It is all fine untill you have to keep native media type and create inherited one with additional properties.
Everything is fine untill you try to do drag and drop upload of mutiple files. By default Umbraco will create native media items (of course they are allowed in target container/folder). As much as you try to trick and override behaviour of mass uploader it does not work.
But, what if you change type of media file after upload. This considers that every container which contains inherited media types needs to allow native media types. I can live with this :).
This solution is based that in custom ApplicationHandler we handle MediaService.Saved event and than we change created item from native to our inherited type.
First we need to write ApplicationHandler and write a handle inside it for Media.Saved event:
public class ApplicationHandler : ApplicationEventHandler { public ApplicationHandler() { MediaService.Saved += new Core.Events.TypedEventHandler<IMediaService, Core.Events.SaveEventArgs<IMedia>>(MediaService_Saved); } }
This will handle all Media.Saved events with MediaService_Saved method.
This means that however you create new media item (whether with drag and drop or manualy throug Umbraco interface) this method will be triggered. Not so complicated logic of the method is the following:
void MediaService_Saved(IMediaService sender, Core.Events.SaveEventArgs<IMedia> e) { foreach (IMedia mediaItem in e.SavedEntities) { if (mediaItem.ContentType.Alias.Equals("Image", StringComparison.InvariantCultureIgnoreCase) && mediaItem.Parent() != null && !mediaItem.Parent().ContentType.Alias.Equals("Folder", StringComparison.InvariantCultureIgnoreCase)) { var firstCustomType = mediaItem.Parent().ContentType.AllowedContentTypes.Where(t => !t.Alias.Equals("Image", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); if (firstCustomType != null) { IMediaType newType = ApplicationContext.Current.Services.ContentTypeService.GetMediaType(firstCustomType.Alias); if (mediaItem.ContentTypeId != newType.Id) { mediaItem.ChangeContentType(newType, true); ApplicationContext.Current.Services.MediaService.Save(mediaItem, 0, false); } } } } }
I usually combine this approach with auto generating cropper images, so if I have ImageCropper property in my custom type, right after upload cropped image files are created. In case I do not do this, I would have to go and save one by one after mass upload. This approach is described in Umbraco Cms posts
References
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
Comments for this article