Search
Close this search box.

How to download files using a Generic Handler

Using a Generic Handler to download files from server has couple of advantages, I list some of them:

1. Download Statistics.

2. Download Tracking.

3. Download Protection.

4. Other business request.

So I suggest that you always use Generic Handler to download files from server.

Here I will show how to implement it.

1. Add Generic Handler and name it to “Download.ashx”.

2. Add code to the download handler

public class Download : IHttpHandler {
  public void ProcessRequest(HttpContext context) {
    // add some logic to validate the user if he has access to download file
    if (context.User.Identity.IsAuthenticated) {
      string file = context.Request.QueryString["file"];
      if (!string.IsNullOrEmpty(file) &&
          File.Exists(context.Server.MapPath(file))) {
        context.Response.Clear();
        context.Response.ContentType = "application/octet-stream";
        // I have set the ContentType to "application/octet-stream" which cover
        // any type of file
        context.Response.AddHeader(
            "content-disposition",
            "attachment;filename=" + Path.GetFileName(file));
        context.Response.WriteFile(context.Server.MapPath(file));
        // here you can do some statistic or tracking
        // you can also implement other business request such as delete the file
        // after download
        context.Response.End();
      } else {
        context.Response.ContentType = "text/plain";
        context.Response.Write("File cannot be found!");
      }
    }
  }

  public bool IsReusable {
    get { return false; }
  }
}

3. Finally we only need to add one line code to download page.

<a href="Download.ashx?file=HelloWorld.txt">Download</a>

Hope this helps!

Thanks for reading!

Wednesday, March 07, 2012 8:42 PM

This article is part of the GWB Archives. Original Author: hmloo

Related Posts