Upload an Image or Any File Using Ajax and the FormData Object

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" />                                  
    </form>                            
</div>  
   
<div id="imgUploadFormAjax" style="display: none; ">
    Uploading...Maybe add an animation gif here
</div>  

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

<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
            $("#imgUploadFormAjax").show();
            $("#fileUpload").hide();                

            e.preventDefault()
            $.ajax({
                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);
                        $("#imgNewImage").show();

                        $("#divUploadForm").hide();                            
                        $("#divNewUploadComplete").show();
                    }                    
                },
                error: function (data)
                {                    
                },
                complete: function (data)
                {
                    $("#imgUploadFormAjax").hide();
                }
            });
        }));        

        $("#fileUpload").on("change", function ()
        {
            $("#frmUpload").submit();
        });
    });       

</script>