How to download a media item in sitecore from a page as “save as”

        private FileField _fileField;
        private Item _item;
        private MediaItem _mediaItem;

_fileField = Sitecore.Context.Item.Fields["File"];

            if (_fileField != null) 
                _item = Sitecore.Context.Item.Database.GetItem(_fileField.MediaID);

            if (_item != null)
                _mediaItem = new MediaItem(_item);

                    if (_mediaItem != null)
                    {

                   Button viewButton = new Button
                        {
                            CssClass = "ButtonCSSClass",
                            Text = "Click here to download the File",
                            ToolTip = "Click here to download the File",
                        };

                        viewButton.CommandArgument = _mediaItem.ID.ToString();
                        viewButton.Command += ViewButton;
                    }




protected void ViewButton_Click(object sender, CommandEventArgs e)
        {
            string mediaId = (String)e.CommandArgument;
            Button button = (Button)sender;

            if (mediaId.IsNullOrEmpty())               
                return;

            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.ContentType = String.Format(mediaItem.MimeType);
                Response.AddHeader("content-disposition", "attachment; filename=" + mediaItem.Name + "." + mediaItem.Extension);
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite(buffer);
                Response.End();
            }
        }
Advertisements

4 thoughts on “How to download a media item in sitecore from a page as “save as”

  1. FYI the filename needs to be wrapped in double quotes. The RFC states this, without them you will find some filenames and browser combinations ignore the header value. Found this out yonks back when working on our old CMS. Best Regards Richard

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s