我正在尝试在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
事件?
答案 0 :(得分:-1)
尝试:
$.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() {
//
}
});