我正在使用 jQuery 上传照片,并为 onprogress 事件附加了一个侦听器。然而,即使上传几兆字节的照片,唯一会触发的 onprogress 事件是当它达到 100% 时。我已经看到像 Dropbox 和 facebook 这样的其他网站显示了更加流畅的进度条。如何更频繁地更新上传进度?
示例上传代码:
var file = $photoFile.get(0).files[0];
var fileBlob = file && file.slice();
var formData = new FormData();
var title = $photoTitle.val();
formData.append('file', fileBlob);
formData.append('title', title);
$.ajax({
url: '/api/v1/photo/submit',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
xhrFields: {
onprogress: function(ev) {
console.info('upload progress', ev);
if (ev.lengthComputable) {
var percentUploaded = Math.floor(ev.loaded * 100 / ev.total);
console.info('Uploaded '+percentUploaded+'%');
// update UI to reflect percentUploaded
} else {
console.info('Uploaded '+ev.loaded+' bytes');
// update UI to reflect bytes uploaded
}
}
}
}).done(function(response) {
// do stuff
}).fail(function() {
// handle error
});