April 25, 2012

HOWTO: POST a file to an .ASHX generic handler

Problem:
You want to be able to POST a file from a generic HTML form to a generic ASP.NET handler (.ashx).

Solution:
First, make sure that your file input control on your HTML form has a name.  If it doesn't have a name, you won't be able to access the file on the server side and it will appear not to have uploaded.

<input name="uploadedFile" id="uploadedFile" type="file" />

Second, make sure that your form action has an enctype parameter set to "multipart/form-data."

<form action="Upload.ashx" method="post" enctype="multipart/form-data" />

Now in your HTTP handler, you can either access that file by the name you provided it on the form:

context.Request.Files["uploadedFile"]

...or you can iterate through the files by key...

foreach (string f in context.Request.Files.AllKeys)
{
  context.Request.Files[f].SaveAs(
    HttpContext.Current.Server.MapPath("~/App_Data/" + ...));
}

No comments: