Five New Optimizely Certifications are Here! Validate your expertise and advance your career with our latest certification exams. Click here to find out more

Determine what media type to create

Vote:
 

I have an upload function where you can upload file to a ContentFolder.

The code looks something like this:

var newFile = _contentRepository.GetDefault<GenericMedia>(dest.Directory.ContentLink);
var blob = _blobFactory.CreateBlob(newFile.BinaryDataContainer, Path.GetExtension(file.FileName));

using (Stream stream = blob.OpenWrite())
{
	file.InputStream.CopyTo(stream);
}

newFile.BinaryData = blob;
_contentRepository.Save(newFile, SaveAction.Publish);

GenericMedia is a base class for media files and then i have a few specialized media types (ImageFile, VideoFile etc) with extra properties.

Instead of always creating generic media i would like to create the correct media type based on the media descriptor attribute in my media types.

    [MediaDescriptor(ExtensionString = "jpg,jpeg,jpe,ico,gif,bmp,png")]
    public class ImageFile : GenericMedia, IContentImage
    {}

Does EPiServer have a function for retrieving the correct media type based on the file extention? Im guessiong something simular is done when uploading a file in edit mode.  

#80062
Jan 14, 2014 15:54
Vote:
 

Yes we have:

var fileInfo = new FileInfo(file.FileName);
var contentTypeRepository = ServiceLocator.Current.GetInstance<IContentTypeRepository>();
var contentMediaResolver = ServiceLocator.Current.GetInstance<ContentMediaResolver>();
ContentType correctMediaType = contentTypeRepository.Load(contentMediaResolver.GetFirstMatching(fileInfo.Extension));

    

After that you just do:

var newFile = ServiceLocator.Current.GetInstance<IContentRepository>().GetDefault<IContentMedia>(dest.Directory.ContentLink, correctMediaType.ID);

        

Hope that help!

//Ha Bui

#80081
Edited, Jan 14, 2014 17:36
Vote:
 
#80082
Jan 14, 2014 17:36
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.