Surendra Sharma

Surendra Sharma

Search This Blog

Friday, August 26, 2016

How to get media library extension and mime type programmatically in Sitecore



One of my colleague asked me that how to get extension of uploaded file in Sitecore media library programmatically?

Here are different pointers which may be useful for you while working with media library 

·         You can get media library item in LinkField type from Sitecore.Data.Fields namespace.

·         LinkField.TargetItem -> gives reference of media library item.

·         Sitecore.Resources.Media.MediaManager.GetMediaUrl(linkField.TargetItem) -> Return media links

·         By default, link extension is “.ashx

·         Get the extension and mime type of media library item by using below code

//Return extension like gif
string mediaItemExtension = linkField.TargetItem.Fields["Extension"].Value;

//Return mime type like image/gif
string mediaItemMimeType = linkField.TargetItem.Fields["Mime Type"].Value;

·         You can also view both of these fields in Sitecore content tree as


Media Item
Media item
  
·         Let me cover one important entry in web.config file for media library item extension.
<!--  MEDIA - USE FILE EXTENSION IN ITEM NAMES
      Indicating whether to include a file extension when generating an item name from a file name.
      Default value: "false"
-->
<setting name="Media.IncludeExtensionsInItemNames" value="false"/>

·         As comments above explain that if you want to include extension in media item name then set this property as true and when you upload any file in media library for example “1.JPG” then after uploading, Sitecore give its name as “1 jpg” as shown in below image. By default this value is false and for uploading “1.JPG”, Sitecore name it as “1” as shown in first image.

Media Item with extension
Media item with extension

Please leave your comments or share these tip if it’s useful for you.

No comments:

Post a Comment