Saturday, December 6, 2014

Download file using HTTP handler

When you are using AJAX in a page and want to modify the response it won’t allow.
So you can write http handler which will handle the request in separate context rather than in the current page context.


C# code:
Finding the control and setting the navigate property to httphandler and passing the id of the file to be downloaded.

((HyperLink)e.Item.FindControl("hlPdf")).NavigateUrl = "Download.ashx?id=" + ID;



//Http handler code for download.ashx

<%@ WebHandler Language="C#" Class="Download" %>

using System;
using System.Web;
using System.Linq;

public class Download : IHttpHandler {
   
    public void ProcessRequest (HttpContext context)
    {
        string id = context.Request.QueryString["id"];
        if (!string.IsNullOrEmpty(id))
        {
            string filename = string.Empty;
            byte[] pdf = null;
           
           // Get the PDF file from the Database here.
            pdf = GetPDF(id, out filename);

            if (pdf != null)
            {
                context.Response.Clear();
                context.Response.ClearHeaders();
                context.Response.ClearContent();
                context.Response.AppendHeader("content-length", pdf.Length.ToString());
                context.Response.ContentType = "application/pdf";
                context.Response.AppendHeader("content-disposition", "attachment; filename=" + filename);
                context.Response.BinaryWrite(pdf);
                context.ApplicationInstance.CompleteRequest();
            }
           
        }
       
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

No comments:

Post a Comment