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();
            }
        }

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

  1. Thank you for the snippet of code, but how does this compare to a regular asp button?

  2. 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

  3. Can i use this also to create custom submit action for sitecore forms to download the item? im getting the stream written on the site page instead of having it downloaded

Leave a reply to shimirel Cancel reply