Upload file asynchronously using JQuery

In this post i am going to show you how to upload a file asynchronously using JQuery.

Using HTML5 we can upload files with Ajax and JQuery. We can also do file validations like name, checking size and file type. We can also handle the progress event. All the above things without using any external plugins.

How to upload a file : 


Assume you have following html. 

<form enctype="multipart/form-data">
    <input name="file_name" type="file" />
    <input id="btnUpload" type="button" value="Upload_File" />
</form>
<progress></progress>

In the above html we have a form in which we have a file upload control and a button to upload the file. We also have a progress tag using which we can track the file upload status.

To do the validation we have to use the onChange event of the fine control.

Validation for file upload :

$(':file').change(function(){
    var file = this.files[0];
    var fileName = file.name;
    var fileSize = file.size;
    var fileType = file.type;
    //Add validation code here
});

In the above code we got the uploaded file's name, size and type. Validation can be done using these properties.

JQuery code to upload the file :

$('#btnUpload').click(function(){
    var formData = new FormData($('form')[0]);
    $.ajax({
        url: 'url for processing file',
        type: 'POST',
        xhr: function() {  // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ // Check if upload property exists
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); 
                // For handling the progress of the upload
            }
            return myXhr;
        },
        //Ajax events
        beforeSend: beforeSendHandler,
        success: completeHandler,
        error: errorHandler,
        // Form data
        data: formData,
        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });
});

Now lets implement the file upload progress handling function

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded,max:e.total});
    }
}

Above code updates the progress tag with the percentage of file uploaded.

In this way we can upload files using JQuery and Ajax.


For any doubts/suggestions please comment in comments section below.

For more posts on JQuery visit: JQuery 

No comments:

Post a Comment