Wednesday, August 27, 2014

Working With Sitecore Media Items

To create media items, sitecore provides two templates for each type of media item, a versionable template and unversionable template. In general, versioning of media should only be implemented when versioning is expressly required and implications such as increased database storage space over time are understood.

Media items can be stored in two ways

Database Media Storage: Media items are stored in database as blob.


Advantages:
  •          Media can be published like any other resource.
  •          CMS services such as locking, security, versioning and workflow are supported for media.
  •          Images can be dynamically manipulated, for instance shrinking or stretching.
  •          Changes to the media library do not need to be synchronized with the file system.

Disadvantages:
  •          Very large media can result in performance issues.
  •          URLs for media items are altered, for instance ending in the .ashx extension which invokes ASP.NET processing rather than original file extensions.
  •          Can result in increased database and file system requirements as media are both stored in two databases (master and web) as well as being cached on disk.

Configuration:
  •          Set Media.UploadAsFiles to false in web.config

 File System Media Storage: Media items are stored on file system. Path of the uploaded file would be stored in “File Path” field in sitecore.

Advantages
  •          Media can be manipulated on the file system, for instance copying the media folder to another system.

Disadvantages
  •          For multi-server environments, media must be propagated from the CMS server to the content delivery servers(s) using the Sitecore Staging module.
  •          CMS services such as locking, security, versioning and workflow can be applied to the metadata only. Every change of the file itself will required a new copy of the file in the file system.

Configuration
  •          Set Media.UploadAsFiles to true in web.config 
           <setting name=”Media.UploadAsFiles” value=”true”>

  •          Specify the MediaFolder path in web.config

           <sc.variable name=”mediaFolder” value=”/upload”>

  •          Specify the Media.FileFolder path. Uploaded files will be stored in this folder

           <setting name=”Media.FileFolder” value=”/App_Data/MediaFiles”>

Programmatically create a media item

        string filePath=@"C:\Images\Translate.png";
        string filenamefull = Path.GetFileName (filePath);
        string noextensionname = Path.GetFileNameWithoutExtension (filePath);
        Database master = Sitecore.Configuration.Factory.GetDatabase ("master");
        Sitecore.Resources.Media.MediaCreatorOptions options = new Sitecore.Resources.Media.MediaCreatorOptions ();
        options.FileBased = false; //stores the file in database, not as file
        options.AlternateText = noextensionname;
        options.Destination = "/sitecore/media library/images/" + noextensionname;
        options.Database = master;
        options.Versioned = false; // Do not make a versioned template
        options.KeepExisting = false; // Overwrite any existing file with the same name
        Sitecore.Data.Items.MediaItem mediaitem = new Sitecore.Resources.Media.MediaCreator ().CreateFromFile (filePath, options);


Retrieve a media item: You can use the Sitecore.Data.Items.MediaItem class to access media items.

        Database master = Sitecore.Configuration.Factory.GetDatabase ("master");
        Item item = master.GetItem ("/sitecore/media library/Images/Translate");
        If (item! = null)
        {
            MediaItem mediaItem = new MediaItem (item);
            img.ImageUrl = Sitecore.Resources.Media.MediaManager.GetMediaUrl (mediaItem);
        }


If the Sitecore Item you are linking to is a Media Item, you cannot use the LinkManager as this will return the URL to the Sitecore item, not the actual media. Instead use the MediaManager.

4 comments:

  1. Hi,

    I want to change the extension of the uploaded media item. Ex: if i upload ".png" file in the singlefileupload popup modal, i it should save with ".jpeg" extension.

    Could you please let me know how to proceed with it, as "mediaitem.extenion" is a get property.
    public void Process(UploadArgs args)
    {
    const string breakLine = @"\r\n";

    foreach(string key in args.Files)
    {
    HttpPostedFile file = args.Files[key];

    if (file!=null && file.FileName.Length > 0 && file.ContentLength > 0)
    {
    string filename = FileUtil.MakePath(args.Folder, Path.GetFileName(file.FileName), '\\');
    try
    {
    if (Path.GetExtension(filename).Equals(".png") )
    {
    file.SaveAs(filename);
    continue;
    }
    if (!args.Overwrite)
    {
    filename = FileUtil.GetUniqueFilename(filename);
    //Bitmap b = (Bitmap)Bitmap.FromStream(file.InputStream);
    //b.Save(filename, ImageFormat.Png);
    //filename = filename.Replace("png","jpeg");
    file.SaveAs(filename);

    }

    // EventDispatcher.DispatchTrace("File has been uploaded: " + filename);
    }
    catch(Exception ex)
    {
    Log.Error("Could not save posted file: " + filename, ex, this);
    }
    }
    }
    }
    }
    }

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. I have added the below pipeline to execute the code,









    ReplyDelete