Force Download of Sitecore Media Item

Here’s some sample code that will force the download of a Sitecore Media Item.

MediaItem mi = CurrentDB.GetItem("/sitecore/media library/Files/Misc/Jim_Beam_vs_Cuervo");

Stream fileStream = mi.GetMediaStream();

byte[] buffer = new byte[fileStream.Length];

fileStream.Read(buffer, 0, (int)fileStream.Length);fileStream.Close();

Response.ContentType = mi.MimeType;Response.AddHeader("content-disposition", "attachment; filename=" +mi.DisplayName + "." + mi.Extension);

Response.BinaryWrite(buffer);

You’ll need the following usings:

using System;
using System.IO;
using Sitecore.Data.Items;

Leave a Reply