Skip to content Skip to sidebar Skip to footer

Using Html5 For File Upload With Ajax And Jquery

So i am trying to upload an image along with form data to server. I'm using FileReader API to convert image to data and upload to server. I'm following the code similar to HTML5 up

Solution 1:

I'm not sure if file upload works with filereaders, but there is a different way to make it work:

var formData = newFormData($(".file_upload_form")[0]);
$.ajax({
    url: "upload_file.php", // server script to process data (POST !!!)type: 'POST',
    xhr: function() { // custom xhr
        myXhr = $.ajaxSettings.xhr();
        if (myXhr.upload) { // check if upload property exists// for handling the progress of the upload
            myXhr.upload.addEventListener('progress', progressHandlingFunction, false); 
        }
        return myXhr;
    },
    success: function(result) {
        console.log($.ajaxSettings.xhr().upload);
        alert(result);
    },
    // Form datadata: formData,
    //Options to tell JQuery not to process data or worry about content-typecache: false,
    contentType: "application/octet-stream", // Helps recognize data as bytesprocessData: false
});

functionprogressHandlingFunction(e) {
    if (e.lengthComputable) {
        $("#progress").text(e.loaded + " / " + e.total);
    }
}

This way you send the data to the PHP file and you can use $_FILES to process it. Unfortunately, this does not work in IE as far as I know. There might be plugins available that make this possible in IE, but I don't know any of them.

Post a Comment for "Using Html5 For File Upload With Ajax And Jquery"