2014-01-31 83 views
2

我在這裏看到了一些類似的帖子,但我似乎無法解決這個問題。基本上,我有一個AJAX文件上傳器,似乎沒有調用進度事件。其他事件觸發得很好,文件上傳完全按照我的預期進行,但進度事件未被調用。 JavaScript的如下所示:文件上傳進度儘管文件已上傳,但事件並未觸發

$('input[name=avatar_upload]').change(function(e) { 
    // Get the Form 
    var setupForm = $('#setup-member-form'); 

    // Get the File Array 
    var file = document.getElementById('avatar-upload').files[0]; 

    // Show the File Upload Progress 
    $('#avatar-upload-progress').show(); 

    // Create a new Form Data Object 
    var formData = new FormData(); 

    // Add the File 
    formData.append('avatar', file); 

    // Create the AJAX Object 
    var ajax = new XMLHttpRequest(); 

    // Add the Event Listeners 
    ajax.addEventListener("loadstart", function(evt) { 
     // Do something in here... 
     $('#output').append("upload starting...\n"); 
    }, false); 
    ajax.addEventListener("progress", function(evt) { 
     var percentLoaded = (evt.loaded/evt.total) * 100; 
     $('#output').append(percentLoaded + "% loaded\n"); 
     $('#avatar-upload-progress .ui-progress-bar-inner').animate({'width' : percentLoaded + '%'}, 400); 
    }, false); 
    ajax.addEventListener("load", function(evt) { 
     // Do something in here when loaded... 
     $('#output').append("upload complete!"); 
    }, false); 

    // Open the Form 
    ajax.open("POST", $('input[name=upload_handler]').val()); 
    ajax.send(formData); 
}); 

起初我以爲這可能只是因爲文件是太小了,progress事件有機會火,但我已經有較大的文件試了一下,和加載事件觸發,然後暫停幾秒鐘,然後完成事件觸發。

如果有人有任何想法,請讓我知道!

回答

5

剛剛經過測試,上傳時必須使用XMLHttpRequest.upload,因爲將事件直接附加到XMLHttpRequest上傳時只會觸發一次。

它在documentation on MDN

$('#avatar-upload').on('change', function() { 
    var file = document.getElementById('avatar-upload').files[0]; 

    $('#avatar-upload-progress').show(); 
    var formData = new FormData(); 
    formData.append('avatar', file); 

    var ajax = new XMLHttpRequest(); 

    ajax.upload.addEventListener("loadstart", function (evt) { 
     $('#output').append("upload starting...\n"); 
    }, false); 

    ajax.upload.addEventListener("progress", function (evt) { 
     var percentLoaded = (evt.loaded/evt.total) * 100; 
     $('#output').append(percentLoaded + "% loaded\n"); 
     $('#avatar-upload-progress .ui-progress-bar-inner').animate({ 
      'width': percentLoaded + '%' 
     }, 400); 
    }, false); 

    ajax.upload.addEventListener("load", function (evt) { 
     $('#output').append("upload complete!"); 
    }, false); 

    ajax.open("POST", $('input[name=upload_handler]').val()); 
    ajax.send(formData); 
}); 
還解釋