1/13/2014 3:40:10 AM

This code creates an ajax file uploader. It uses the FormData object. The FormData object is not supported by all browsers.

<div id="divUploadForm">    
    <form method="post" enctype="multipart/form-data" id="frmUpload" action="/home/ajaxupload/">        
        <input name="file" type="file" id="fileUpload" />                                  
<div id="imgUploadFormAjax" style="display: none; ">
    Uploading...Maybe add an animation gif here

<div id="divNewUploadComplete" style="display: none; ">
    <img id="imgNewImage" />  

<script type="text/javascript">

    $(document).ready(function ()
        $('#frmUpload').on('submit', (function (e)
            var formData = new FormData();          

            //get all form data at once
            formData = new FormData(document.forms.namedItem("frmUpload"));            

            //ajax animation

                type: 'POST',
                url: '/home/ajaxupload/',
                data: formData,
                cache: false,
                processData: false,
                contentType: false,
                success: function (data)
                    //NewFileVirtualPath needs to be returned by your server code
                    if (data.NewFileVirtualPath != null)
                        //show image                                                
                        $("#imgNewImage").attr("src", data.NewFileVirtualPath);

                error: function (data)
                complete: function (data)

        $("#fileUpload").on("change", function ()