Quantcast
Channel: .notes » asp.net
Viewing all articles
Browse latest Browse all 8

Easy Asp.net ajax file upload

$
0
0

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.



Viewing all articles
Browse latest Browse all 8

Trending Articles