0

サーバーに画像をアップロードするために Ajax リクエストを使用しています。これらのコードを使用していますが、動作しますが、100% しか返されず、他のパーセンテージは返されません。私は何をすべきか?

$('#uploadImgForm').change(function(e){
        var th = $(this);
        $.ajax({
            url: "post/imageInsert.php",
            type: "POST",
            data:  new FormData(this),
            dataType: 'json',
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function(){
                $("#imgBack").html('uploading').show();
            },
            xhr: function()
            {
                var xhr = new window.XMLHttpRequest();
                //Upload progress
                xhr.upload.addEventListener("progress", function(evt){

                    if (evt.lengthComputable) {
                        var percentComplete = Math.floor(evt.loaded / evt.total) * 100 + '%';
                        $('#progress').css({width : percentComplete});
                    }
                }, false);


                return xhr;
            },
            success: function(data){
                if(!data['error']) $("#imgBack").html($('<img>').attr('src',data['success']));
                else $("#imgBack").html(data['error']);
            },
            error: function(){
                $("#imgBack").html('Error').hide();
            }
        });
    });
4

2 に答える 2

0

私は最近同じことを行いました(画像のアップロードが完了した割合を示す進行状況バーを作成します)。次のコードが機能します。試してみてください:

$("#uploadImgForm").on("submit", upload_image);

function update(evt){
    var percentComplete = Math.floor(evt.loaded / evt.total) * 100 + '%';
    $('#progress').css({width : percentComplete});
}

 function upload_image(event){
    event = event || window.event;
    // Prevent the default form action i.e. loading of a new page
    if(event.preventDefault){ // W3C Variant
        event.preventDefault();
    }
    else{ // IE < 9
        event.returnValue = false;
    }
    $.ajax({
        url: "post/imageInsert.php",
        type: "POST",
        data: new FormData($('#uploadImgForm')[0]), 

        beforeSend: function(){
            $("#imgBack").html('uploading').show();
        },

        xhr: function(){
            // get the native XmlHttpRequest object
            var xhr = $.ajaxSettings.xhr() ;
            // set the onprogress event handler
            xhr.upload.onprogress = update,
            // set the onload event handler
            xhr.upload.onload = function(){ } ;
            // return the customized object
            return xhr ;
        },
        success: function(data){
            if(!data['error']) $("#imgBack").html($('<img>').attr('src',data['success']));
            else $("#imgBack").html(data['error']);
        },
        error: function(){
            $("#imgBack").html('Error').hide();
        },

        enctype: 'multipart/form-data',
        processData: false,
        contentType: false,
        cache: false
    });
 }
于 2015-04-22T10:09:39.950 に答える