PM's Blog

Pramod Mohanan's notes about ASP.NET, MVC, C#, SQL, jQuery, Bootstrap

HttpHandler to handle image uploads at server

The following module is useful to handle image uploads at the server especially when not using the default upload controls. It can be affectively used for hanlding ajax image uploads. The following handler returns Html content(true or false) based on the result of the upload.

public class Upload : IHttpHandler
{
   public void ProcessRequest(HttpContext context)
   {
      string fileName;
      string UserImage = ConfigurationManager.AppSettings["SiteImagesLocation"]; // physical location from config file
      context.Response.ContentType = "text/html";
      context.Response.Expires = -1;
      try
         {
           HttpPostedFile postedFile = context.Request.Files["upload"];
           UserImage += postedFile.FileName;
           postedFile.SaveAs(UserImage);
           context.Response.Write("true");
         }
         catch (Exception ex)
         {
         try //this is for non IE browsers
         {
            int length = 4096;
            int bytesRead = 0;
            Byte[] buffer = new byte[length];
            UserImage += context.Request.QueryString["upload"];
            using (FileStream fileStream = new FileStream(UserImage, FileMode.CreateNew))
            {
              do
              {
                bytesRead = context.Request.InputStream.Read(buffer, 0, length);
                fileStream.Write(buffer, 0, bytesRead);
               } while (bytesRead > 0);
             }
             context.Response.Write("true");
           }
           catch (Exception exc)
           {
              context.Response.Write("false");
         }
      }
  }

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

The above handler when used along with Resising of Images can turn out to be quite a killer solution for handling resizing images upload specially for Ajax based image uploaders.

Leave a Reply

Your email address will not be published. Required fields are marked *

PM's Blog © 2015