Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ASP.NET Server Side Handler for HTML5 Valums Ajax file Upload

0.00/5 (No votes)
27 May 2011 1  
Implementation of ASP.NET handler for Valums ajax upload; A HTML 5 file uploader supports multiple file upload with progress bar, drag-and-drop

Introduction

This Ajax uploader uses XHR for uploading multiple files with progress-bar in FF3.6+, Safari4+, Chrome and falls back to hidden iframe based upload in other browsers, providing good user experience everywhere. You can also see PHP demo in Valums site at http://valums.com/ajax-upload/.

AjaxUpload.JPG

Background

The current implementation has server side handler for Java, PHP and Perl. But ASP.NET handler does not exist. Here, I have implemented an ASP.NET handler for Ajax file upload that supports Internet Explorer, Firefox and Chrome. 

Using the Code

The problem is that Internet Explorer uses 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 works in Firefox and Chrome is as follows:

//This works for Firefox and Chrome.
Stream inputStream = 
HttpContext.Current.Request.InputStream;<br />FileStream fileStream = new 
FileStream(mapPath + "\\" + filename, 
FileMode.OpenOrCreate);inputStream.CopyTo(fileStream);fileStream.Close();

context.Response.Write("{success:true, name:\"" + filename + "\", path:\"" + 
path + "/" + filename + "\"}");

But for Internet Explorer, you need to use:

HttpPostedFile uploadedfile = context.Request.Files[0];

Code that works for Internet Explorer browser is:

HttpPostedFile uploadedfile = context.Request.Files[0];
 filename = uploadedfile.FileName;
uploadedfile.SaveAs(mapPath + "\\" + filename);
 context.Response.Write("{success:true, name:\"" + filename + "\", path:\"" + 
path + "/" + filename + "\"}");

Here the response is sent 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

History

  • 27th May, 2011: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here