我正在尝试在AJAX文件上传过程中显示进度栏:

var data = new FormData();
    data.append('name', file.name); //something.jpg
    data.append('upload', blob); //data:image/jpeg;base64,/sd5a4de42qeasQW3123....

$.ajax({
    type: 'POST',
    url: '/path/to/server/',
    data: data,
    dataType: 'json',
    cache: false,
    processData: false,
    contentType: false,
    xhr: function() {

        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener('progress', function(e) {
            // THIS IS ONLY RUNS ONCE!!!
            if(e.lengthComputable) {
                $('#progressbar').css('width', (e.loaded / e.total) * 100 + '%');
            }
        }, false);
        return xhr;

    },
    beforeSend: function() {
        $('.preview').addClass('uploading');
    },
    success: function(response) {
        if(response.success) {
            $('.preview')
                .removeClass('uploading')
                .addClass('uploaded');
        } else {
            // Fail
        }
    },
    error: function() {
        //
    }
});

问题是进度条直接跳到100%,而不是逐渐上升1%... 24%... 50 ...等。

在上面的代码中,请查找此注释// THIS IS ONLY RUNS ONCE!!!。如何使progress事件正常启动?

最佳答案

尝试:

$.ajax({
    type: 'POST',
    url: '/path/to/server/',
    data: data,
    dataType: 'json',
    cache: false,
    processData: false,
    contentType: false,
    beforeSend: function(xhr){
        xhr.upload.addEventListener('progress', function(e) {
            // THIS IS ONLY RUNS ONCE!!!
            if(e.lengthComputable) {
                $('#progressbar').css('width', (e.loaded / e.total) * 100 + '%');
            }
        }, false);
        return xhr;
        $('.preview').addClass('uploading');
    },
    success: function(response) {
        if(response.success) {
            $('.preview')
                .removeClass('uploading')
                .addClass('uploaded');
        } else {
            // Fail
        }
    },
    error: function() {
        //
    }
});

09-12 07:28