The current implementation has server side handler for java, php and Perl. But does not exist Asp.net handler. Here I have implemented a Asp.net handler for ajax file upload that supports IE, Firefox and Chrome.
Problem is IE use context.Request.Files[] for sending file to server. But Firefox and Chrome use Context.Request.InputStream. So in handler you need to check both for reading stream.
For Firefox and Chrome you get fileName from header like
String filename = HttpContext.Current.Request.Headers["X-File-Name"];Code that work in Firefox and Chrome
//This work for Firefox and Chrome.But for IE you need to use
Stream inputStream = HttpContext.Current.Request.InputStream;
FileStream fileStream = new FileStream(mapPath + "\\" + filename, FileMode.OpenOrCreate);
inputStream.CopyTo(fileStream);
fileStream.Close();
context.Response.Write("{success:true, name:\"" + filename + "\", path:\"" + path + "/" + filename + "\"}");
HttpPostedFile uploadedfile = context.Request.Files[0];Code that work for IE browser :
HttpPostedFile uploadedfile = context.Request.Files[0];Here the response is send as JSON string and you will get JSON object as response. you need to send {success:true} to make ajax upload understand that file upload is successful otherwise you can send false.
filename = uploadedfile.FileName;
uploadedfile.SaveAs(mapPath + "\\" + filename);
context.Response.Write("{success:true, name:\"" + filename + "\", path:\"" + path + "/" + filename + "\"}");
Complete code is:
public void ProcessRequest(HttpContext context)
{
const string path = "Capture/Images";
String filename = HttpContext.Current.Request.Headers["X-File-Name"];
if (string.IsNullOrEmpty(filename) && HttpContext.Current.Request.Files.Count <= 0)
{
context.Response.Write("{success:false}");
}
else
{
string mapPath = HttpContext.Current.Server.MapPath(path);
if (Directory.Exists(mapPath) == false)
{
Directory.CreateDirectory(mapPath);
}
if (filename == null)
{
//This work for IE
try
{
HttpPostedFile uploadedfile = context.Request.Files[0];
filename = uploadedfile.FileName;
uploadedfile.SaveAs(mapPath + "\\" + filename);
context.Response.Write("{success:true, name:\"" + filename + "\", path:\"" + path + "/" + filename + "\"}");
}
catch (Exception)
{
context.Response.Write("{success:false}");
}
}
else
{
//This work for Firefox and Chrome.
FileStream fileStream = new FileStream(mapPath + "\\" + filename, FileMode.OpenOrCreate);
try
{
Stream inputStream = HttpContext.Current.Request.InputStream;
inputStream.CopyTo(fileStream);
context.Response.Write("{success:true, name:\"" + filename + "\", path:\"" + path + "/" + filename + "\"}");
}
catch (Exception)
{
context.Response.Write("{success:false}");
}
finally
{
fileStream.Close();
}
}
}
}
Complete solution is available in codeproject http://www.codeproject.com/KB/aspnet/AspNetHandlerAjaxUpload.aspx