File uploads: Percentage completed progress bar

前端 未结 4 1953
被撕碎了的回忆
被撕碎了的回忆 2021-02-05 16:37

I\'m trying to add a \'percentage completed so far\' progress bar to avatar uploads in BuddyPress. The aim is to stop users navigating away from the page before the upload is co

4条回答
  •  深忆病人
    2021-02-05 17:29

    You should use an XHR object. I don't now if it helps you, but I have a simple XHR uploader written.

    HTML:

        

    JS:

    $("#uploader").submit(function(){
        $('#uploader .list').fadeIn(100).css("width","0px");
        var data = new FormData();
        // if you want to append any other data: data.append("ID","");
        $.each($('#file')[0].files, function(i, file) {
            data.append('file-'+i, file);
        });
        $.ajax({
            url: 'uploadimage.php',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            xhr: function() {  // custom xhr
                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;
            },
            success: function(data2){
                $('#uploader .list').css({
                    "width":"200px",
                    "text-align":"center",
                    "margin":"10px 0 10px 0"
                }).html("DONE!").delay(2000).fadeOut(500);
                if (data2 == "ERROR_FILESIZE"){
                    return alert("Choose another file");
                }
                                else{ /*change location*/ }
            });
        return false;
    });
    

    In this case I uploaded the file with uploadimage.php and if it printed: "ERROR_FILESIZE" then it alerted the error.

提交回复
热议问题