Sitecore Media Item download

Looking for a code that helps you download Media items from sitecore? This post might help you.

Based on a project requirement I was asked to work on a functionality for having a download brochure drop down. A thought might have come to your mind why a drop down for downloading brochures, well my mind too said “what a wired request?”. Why not we just display links for the brochures. But we need to follow the designs and respect client’s requirements. So I created a drop down which displayed items that comes from a multilist field.
Initially I had the media item’s url as the options value for my drop down, but then came across GetMediaStream() method which does the work for getting a media item into a stream so I tweaked my approach and passed item ID in the value for options.

protected void Page_Load(object sender, EventArgs e)
{
  Item currentItem = Sitecore.Context.Item;
  if (currentItem.Fields["MultiListField"] == null) return;

  MultilistField mltFld = currentItem.Fields["MultiListField"];
  foreach (var item in mltFld.GetItems())
  {
                ddlDownloadBrochure.Items.Add(new ListItem(item.Name, item.ID.ToString()));
  }
}
protected void ddlDownloadBrochure_SelectedIndexChanged(object sender, EventArgs e)
{
  if (ddlDownloadBrochure.SelectedValue == null || ddlDownloadBrochure.SelectedValue == "0") return;

  PromptDownloadBrochure(ddlDownloadBrochure.SelectedValue);
}

Below is the method that will fetch all the details of media item, including name, extension and push it back as response.

private void PromptDownloadBrochure(string mediaID)
        {
            ID id = new ID(mediaID);
            if (id.IsNull)
                return;

            MediaItem mediaItem = Sitecore.Context.Database.Items.GetItem(id);
            if (mediaItem != null)
            {
                Stream stream = mediaItem.GetMediaStream();
                long fileSize = stream.Length;
                byte[] buffer = new byte[(int)fileSize];
                stream.Read(buffer, 0, (int)stream.Length);
                stream.Close();
                Response.Clear();
                Response.CacheControl = "public";
                Response.ContentType = "application/octet-stream";

                Response.AddHeader("content-disposition", "attachment; filename=" + mediaItem.Name + "." + mediaItem.Extension);
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite(buffer);
                Response.End();
            }
        }

You can allow the download on a button click or any other asp.net control which does a post back.

Leave a Reply

Your email address will not be published. Required fields are marked *