I would like to create a web part that will reside in the dispform.aspx in a document library. When the user presses a customized button it should be able to download the file but with a different name.

Does anyone has a sample code?

  • When the user presses a customized button it should be able to download the file Which file you need to download? Sep 7 '17 at 10:15
  • The file that its properties is shown in dispform
    – XristosK
    Sep 7 '17 at 11:21

You can create your own ashx-handler in _layouts folder. This handler will be responsible for starting download:

public class TestHandler: IHttpHandler
    public bool IsReusable
        get { return true; }

    public void ProcessRequest(HttpContext context)
        //file itemId in document library 
        string itemId = context.Request.QueryString["itemId"];

        //your document library guid
        string listGuid = context.Request.QueryString["listGuid"];

        byte[] fileContents = null;
        using (SPSite site = new SPSite(SPContext.Current.Site.ID)
             using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID)
                 SPFile file = //here you get you file by listGuid and itemId
                 if (file.Exists)
                    fileContents = file.OpenBinary(SPOpenBinaryOptions.SkipVirusScan);

        //name  what you want
        string fileName = "MY_NAME.Extention";

        //starting downloading file 
        context.Response.ContentType = IMAGE_MIMETYPE;
        context.Response.Headers["content-disposition"] = string.Format("attachment;filename={0}", fileName);

After your handler is ready, you need to generate a link to your handler with file item id and list id (or list name), like "/_layouts/15/MyProject/TestHandler.ashx?fileId={0}&listGuid={1}". When custom button pressed - you're following this link and downloads the file with your name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.