Tuesday, 17 November 2015

Enable Save As option in Sharepoint for browser.

Will not see "Save As" option when we download any document from sharepoint document library. It  will be shown when we click on "Download a copy" in SharePoint ribbon.

Refer below link for enable "Save As" option for browser.
Link

Using Above link we can enable a "Save As" option in IE but it will prompt for user credentials i.e. not work for anonymous users.

For anonymous User , we need to write code as below.

Add Application page and write below code.

Note : Class should inherit with UnsecuredLayoutsPageBase .

 public partial class DownloadFile : UnsecuredLayoutsPageBase
    {
        protected override bool AllowAnonymousAccess
        {
            get
            {
                return true;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                try
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.Url, SPUserToken.SystemAccount))
                    {
                        string path = Request.QueryString["path"];
                        string documentId = Request.QueryString["DocumentId"];
                        string fileName = string.Empty;

                        if (path != null && path.Length > 0)
                        {
                            int lastIndex = path.LastIndexOf("/");
                            fileName = path.Substring(lastIndex + 1, (path.Length - lastIndex - 1));

                            byte[] binfile = SPContext.Current.Web.Lists["Tools"].GetItemById(Convert.ToInt32(documentId)).File.OpenBinary(SPOpenBinaryOptions.None);

                            Response.Clear();
                            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
                            Response.BinaryWrite(binfile);
                            Response.Flush();
                            Response.End();
                        }
                    }
                }
                catch (Exception ex)
                {
                    // do nothing;
                }
            }
        }


    }

No comments:

Post a Comment