Tuesday, 19 August 2014

Download file on html page use handler file

html code

    <a  id="downloadfile" href='pdfHandlerfile.ashx?filename=file1.pdf' target="_self" >download</a>
---------------------------------------------------------
<%@ WebHandler Language="C#" Class="pdf_Handler" %>

using System;
using System.Web;
using System.IO;
 
public class pdfHandlerfile : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
     
    if( HttpContext.Current.Request.QueryString["filename"] !=null)
        PDFdownload(HttpContext.Current.Request.QueryString["filename"].ToString());
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

    public void PDFdownload(string filename)
    {
        try
        {

            string contentType = "Application/pdf";
            HttpContext.Current.Response.ContentType = contentType;
            HttpContext.Current.Response.AppendHeader("content-disposition", "attachment; filename="+filename+"");

            //Write the file directly to the HTTP content output stream.
            HttpContext.Current.Response.WriteFile(HttpContext.Current.Server.MapPath(filename));
            HttpContext.Current.Response.End();
        }
        catch (Exception ex)
        {
        }
    }

}

No comments:

Post a Comment