Monday, August 19, 2013

How can I upload files asynchronously with jQuery


With HTML5 you CAN make file uploads with Ajax and jQuery. Not only that, you can do file validations (name, size, and MIME-type) or handle the progress eventwith the HTML5 progress tag (or a div).

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<form enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>

<div class="progress_bar"
     style="width: 300px; height: 20px; background-color: blue; position: relative;">
    <div class="full" style="width: 0%;
    height: 20px; background-color: red;"></div>
    <div class="text"
         style="color: #ffffff; font-weight: bold; text-align: center;
         position: absolute; left: 109px; top: 0;">Uploading...</div>
</div>
<script type="text/javascript">
    jQuery(document).ready(function() {
        $(':button').click(function(){
            var formData = new FormData($('form')[0]);
            $.ajax({
                url: 'upload.php',  //Server script to process data
                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: function() {
                    console.log("Before send...");
                    var $div = jQuery("div.progress_bar");
                    $div.find("div.full").css({
                        width: "0%"
                    });
                },
                success: function(data) {
                    console.log(data);
                    console.log("Success...");
                    var $div = jQuery("div.progress_bar");
                    $div.find("div.text").html("Uploaded.");
                },
                error: function() {
                    console.log("Error...");
                },
                // Form data
                data: formData,
                //Options to tell jQuery not to process data or worry about content-type.
                cache: false,
                contentType: false,
                processData: false
            });
        });
    });
    function progressHandlingFunction(e){
        console.log(e);
        if(e.lengthComputable){
            var $div = jQuery("div.progress_bar");
            var p = e.loaded / e.total * 100;
            $div.find("div.full").css({
                width: p + "%"
            });
            console.log(p);
        }
    }
</script>


As you can see, with HTML5 (and some research) file uploading not only becomes possible but super easy. Try it with Google Chrome as some of the HTML5 components of the examples aren't available in every browser. 

No comments:

Post a Comment