65.9K
CodeProject is changing. Read more.
Home

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

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.55/5 (14 votes)

May 27, 2011

CPOL

1 min read

viewsIcon

93753

downloadIcon

5529

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