Filehandler in asp.net

Create an ASHX (faster than aspx onload event) page, pass a the id of the file as a querystring to track each download

 public class FileDownload : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
        {
            //Track your id
            string id = context.Request.QueryString["id"];
            //save into the database 
            string fileName = "YOUR-FILE.pdf";
            context.Response.Clear();
            context.Response.ContentType = "application/pdf";
            context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
            context.Response.TransmitFile(filePath + fileName);
            context.Response.End();
           //download the file
        }

in your html should be something like this

<a href="https://stackoverflow.com/GetFile.ashx?id=7" target="_blank">

or

window.location = "GetFile.ashx?id=7";

but I’d prefer to stick to the link solution.

Leave a Comment