Fremus.co.za

Demistifying Life and Web Development

Uploading files with a generic handler (.ashx)

In recent times, the last year or so, I have come to move away from web forms and move more towards an architecture that involves plain html combined with web services or in some cases generic handlers. I like this approach because it allows me to perfectly control the quality of the HTML that is rendered, which in turn is good for a few reasons, one being search engines and the other being true to web standards (or at least trying to). Its relatively easy to combine an asynchronous call with an ASHX file. ASHX files are lighter in terms of processing than their ASPX counterparts. With that in mind I decided to write or create a generic handler based on Scott Hanselman’s example here. And it works! Thats the key thing.

First create an HTML file and add code for a form like this:

Then you create the code in the ASHX file like this:

        string savedFileName = "";

        foreach(string file in context.Request.Files)
        {
            HttpPostedFile hpf = context.Request.Files[file] as HttpPostedFile;
            if (hpf.ContentLength == 0)
                continue;
            savedFileName = context.Server.MapPath(Path.GetFileName(hpf.FileName));
            hpf.SaveAs(savedFileName);
        }
        context.Response.Write(savedFileName);
  • Share/Bookmark
posted by fr3dr1k in ASP.NET,C# and have No Comments
Tags:

Place your comment

Please fill your data and comment below.
Name
Email
Website
Your comment
Get Adobe Flash playerPlugin by wpburn.com wordpress themes