using html5 for file upload with ajax and jquery

后端 未结 1 982
半阙折子戏
半阙折子戏 2021-02-04 21:27

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 HTM

相关标签:
1条回答
  • 2021-02-04 22:08

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

    var formData = new FormData($(".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 data
        data: formData,
        //Options to tell JQuery not to process data or worry about content-type
        cache: false,
        contentType: "application/octet-stream", // Helps recognize data as bytes
        processData: false
    });
    
    function progressHandlingFunction(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.

    0 讨论(0)
提交回复
热议问题