Handling File Upload using ASP.NET ASHX

On a recent project, I needed to do a Web-based file upload. On the client side I decided to use plain vanilla HTML and JavaScript, as opposed to a commercial or open source library, or jQuery, or Flash.

On the server side, to accept a file upload and save it, there were also many options. Two leading options for my particular scenario were a PHP handler, and an ASP.NET ASHX handler.


I hadn’t worked with ASHX before. ASHX is a generic handler, meaning it’s very raw and is designed to do general purpose things with an HTTP request from a client, as opposed to being designed to generate a specific kind of a response such as a Web page.

Anyway, I was pleasantly surprised that, even though ASHX scripts do have a certain amount of overkill abstraction that’s common to all ASP.NET technologies, using ASHX was not as bad as I’d feared it’d be.

The code is quite self-explanatory:

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

using System;
using System.Web;

public class Handler : IHttpHandler {

  public void ProcessRequest (HttpContext context) {
    //context.Response.ContentType = "text/plain";
    //context.Response.Write("Hello World");

      HttpPostedFile postedFile = context.Request.Files[0];
      if (postedFile.ContentLength == 0)
        throw new Exception("Empty file received");

      // cannot restrict accept type on client
      //if (postedFile.ContentType == "image/png")  
      //  throw new Exception("PNG files not allowed");


      string fn = System.IO.Path.GetFileName(postedFile.FileName);
      // to save in 'App_Data':
      // string path =  
      //   HttpContext.Current.Server.MapPath("~/App_Data/");
      postedFile.SaveAs("C:\\Data\\Junk\\Uploads2\\" + fn);
      context.Response.Write("Server received " + fn);  //
    catch (Exception ex)
      context.Response.Write("Error occurred on server " +

  } // ProcessRequest

  public bool IsReusable {
    get {
      return false;

} // class Handler

In general I try to avoid ASP.NET technologies, but handling a file upload using ASHX is a good way to go in a scenario where you’re working Microsoft Web (IIS and ASP.NET) technologies.

This entry was posted in Miscellaneous. Bookmark the permalink.