Friday, January 30

With HTML5 file uploads with Ajax and jQuery.

The HTML:
    <form enctype="multipart/form-data">
        <input name="file" type="file" />
        <input type="button" value="Upload" />
    </form>
    <progress></progress>
 
Do some validation if you want. For example, in the onChange event of the file:

    jQuery(':file').change(function(){
        var file = this.files[0];
        var name = file.name;
        var size = file.size;
        var type = file.type;
        //Your validation
    });

file validations (name, size, and MIME-type) or handle the progress event with the HTML5 progress tag (or a div).


Ajax submit with the button's click:

    jQuery(':button').click(function(){
        var formData = new FormData(jQuery('form')[0]);
        jQuery.ajax({
            url: 'upload.php',  //Server script to process data
            type: 'POST',
            xhr: function() {  // Custom XMLHttpRequest
                var myXhr = jQuery.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
        });
    });
 
 
To handle the progress:

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

No comments:

Post a Comment