Easy Asp.net ajax file upload

Here’s a simple way to get file uploading without the widraw of a postback: it is the asp.net implementation (with a few changes) of the following jQuery plugin.

  1. An image is uploaded and the form submitted.
  2. The submitted form is sent to a custom handler (ashx).
  3. The image is saved to a website folder and the url of the image sent back to the client.
  4. A thumbnail of the image is displayed on the page.

The page contains the preview area for the image, the upload button and of course the references to scripts and styles:

<link href="scripts/plugins/ajaxuploader/fileuploader.css" rel="stylesheet" type="text/css" />
<script src="scripts/jQuery.js" type="text/javascript"></script>
<script src="scripts/plugins/ajaxuploader/ajaxupload.js" type="text/javascript"></script>
<script src="scripts/myScript.js" type="text/javascript"></script>
.........
<div class="mainCont">
            <div class="preview">
                <img id="thumb" width="100px" height="100px" src="images/yellowpuppet.jpg" class="none"/>
            </div>
            <span class="uploadFiles">
                    <label>Select a picture to upload</label>
                    <input type="file" id="imageUpload" size="20" />
            </span>
</div>
The script myScript.js is in charge of creating the AjaxUpload plugin, add the loading effect on the preview and disabling the button during uploading:
$(document).ready(function () {
    var thumb = $('img#thumb');

    new AjaxUpload('imageUpload', {
        action: '../../ImageManager.ashx',
        name: 'myFile',
        onSubmit: function (file, extension) {
            $('div.preview').addClass('loading');
            this.disable();

        },
        onComplete: function (file, response) {
            thumb.load(function () {
                $('div.preview').removeClass('loading');
                thumb.unbind();
            });
            var resp = response;
            resp = $(resp).html();
            thumb.attr('src', resp);
            this.enable();
        }
    });
});

A custom hanlder (ImageManager.ashx) will process the request, get the bytestream of the image and save it to disk, once this is done the url of the image is returned to the clientbrowser and the preview is shown.

public void ProcessRequest(HttpContext context)
{
  HttpPostedFile postedFile = context.Request.Files["myfile"];
  string fileName = postedFile.FileName;
  byte[] fileBytes = new byte[postedFile.ContentLength];
  var fullFileName = _uploadFolder + fileName;
  if (File.Exists(fullFileName))
      File.Delete(fullFileName);

  using (Stream fileInputStream = postedFile.InputStream)
  {
      fileInputStream.Read(fileBytes, 0, postedFile.ContentLength);
  }
  File.WriteAllBytes(fullFileName, fileBytes);
  Uri uriSiteRoot = new Uri(context.Request.Url.GetLeftPart(UriPartial.Authority));
  var output = string.Format("{0}images/uploaded/{1}", uriSiteRoot, fileName);
  context.Response.ContentType = "text/plain";
  context.Response.Write(output);
}

Update: use the following in order to read the bytestream from the request.

byte[] fileBytes = new byte[context.Request.GetBufferlessInputStream().Length];
context.Request.GetBufferlessInputStream().Read(fileBytes,0, fileBytes.Length);

image image image image

The solution contains two projects: one uses an hidden iframe while the other one uses XHR requests.  Download source code.




18 Comments

Hi Tomas,
The project have been build using VS2010, sorry but I don’t have VS2008 installed.
Just create an empty project and paste the files you need, should be pretty straightforward as the files in the sample are really a few.

There are two missing parts in your example:

1. The file is loaded to memory and then saved to disc. This can cause out of memory on large files.
2. There is no progress implementation.

Hi,

1. I’ve refactored the streamreading part, I’ve missed the Read method on the stream in the request. In addition to MaxRequestLength (limit the filesize upload) , the stream in the request, if larger than a certain num of kb, is buffered on disk by default in order to avoid memory overflows.

2. The purpose of the sample is to shows a quick way to implement a file upload using an XHR request. A detailed guide on how to setup the jQuery plugin can be found on the author website, it includes progress, styling of the controls etc. The link is in the post.

2. There is no information how to read and send information of uploaded file size to jQuery plug-in from ASP.NET. That’s really complicated and if you could expand demo with progress bar that would be cool.

Sorry but I am not sure what comments should be uncommented and what is fileuploader? I can’t find such file. Also there is no .NET code in your example which would send file progress back to AjaxUpload.

Hi Tomas,
The file is in the project, look in ..AjaxFileUploadAjaxFileUpload.Web.NoIFramescriptspluginsajaxuploader
You will find the file fileuploader.css .
Open it and remove the comments, you will then have the progression status of the upload displayed.
The progression is handled by the jQuery plugin not from .Net.

i get error Microsoft JScript runtime error: ‘AjaxUpload’ is undefined
when i add

but in
new AjaxUpload(‘imageUpload’, {
action: ‘LoadImages.ashx’,
name: ‘myFile’,
onSubmit: function(file, extension) {
$(‘div.preview’).addClass(‘loading’);
this.disable();
in script function this error appear how can i solve it
thanks

Microsoft JScript runtime error: ‘AjaxUpload’ is undefined
i add in my application

and error appear in
new AjaxUpload(‘imageUpload’, {
action: ‘LoadImages.ashx’,
name: ‘myFile’,
onSubmit: function(file, extension) {
$(‘div.preview’).addClass(‘loading’);
this.disable();
in script function this error appear how can i solve it
thanks

there is problem
yes i use this project by VS2008
and it run to me
but the problem is after load give me Faild and when go to see Picture it opend by x and red color wich meen there is error in loading and
size to normal image is 40.5 KB (41,539 bytes) and after loading
it found on server 195 KB (200,557 bytes)
what the error

Plz Helo ME
there is problem
yes i use this project by VS2008
and it run with me
but the problem is after load give me Faild and when go to see Picture it opend by x and red color which mean there is error in loading and
size to normal image is 40.5 KB (41,539 bytes) and after loading
it found it on server 195 KB (200,557 bytes)
what the error

Leave a Reply

Your email address will not be published. Required fields are marked *